I am unable to map error from lambda to Status Code 400.
My lambda code in Go is as follows
package main
import (
"errors"
"github.com/aws/aws-lambda-go/lambda"
)
func main() {
lambda.Start(returnError)
}
func returnError() error {
return errors.New("Something went wrong!")
}
I have added Response Integration to Status Code 400 as follows.
Still I get response Status Code 200 as follows. I want it to be 400
I am already using mapping template for request and response. I want to separate Lambda from mapping & validation.
You need to setup Lambda as Proxy integration and then write to return status code from lambda as 400.
Here is an existing post:
Is there a way to change the http status codes returned by Amazon API Gateway?
Related
I am using ALB as a trigger for lambda function, when I post request to the alb, I can see the trigger request in cloud watch, however, there's no response to the post request I posted using postman.
I added logs in the code to check it enters the lambda or not but I can't see python logs. Also, I added a role with ElasticLoadBalancingFullAccess to lambda. but still no response; I am not sure how to debug or move on further I tried multiple things, I even added context.done(respons) to the lambda handler, I also changed the format to be json format returns the status code and the body. Any insights will be appreciated.
EDIT:
details about ALB:
listeners: port 80
target: lambda type and I choose my lambda function
security group: simple security groups allow public access (it works fine as I am triggering the lambda by the request)
lambda code:
def lambda_handler(event,context):
# Initialize you log configuration using the base class
context.succeed({
'statusCode': 200,
'body': json.dumps("wuccedd")
})
also I noticed when I put an error intentially in the lambda function like this forexample:
def lambda_handler(event,context):
#error
x= 10/0,,,,,
context.succeed({
'statusCode': 200,
'body': json.dumps("wuccedd")
})
and this also kept the request stuck, which means it doesn't enter the handler function, any idea why the function can be triggered in cloud watch but the handler function isn't entered
We are using below set up for AWS Lambda function.
1 Lambda type - Proxy lambda
2 Handler - org.springframework.cloud.function.adapter.aws.FunctionInvoker
3 Using spring cloud functions for implementing core logic
4 Tried returning below objects as a return type by setting explicitly custom http status code
APIGatewayProxyResponseEvent
Message>
I always get 200 irrespective whatever I set in the response object.
I am stuck on how I should begin my lambda handler that will read some data from dynamodb. I have defined my api gateway model with the requests and response models, therefore do I need to state any status codes in the lambda handler ? Do I use API gateway proxy response event ? Any code examples
in Java would be helpful.
My notes on what I should include in the lambda handler:
access DB
map over table
Find attribute
Return response to api ?
What am I missing ? Thank you.
If you decided to use a non-proxy Lambda integration then you need to define an integration response using a regex. Here is an example using nodeJS:
lambda regex
Normally i declare my error messages just like this:
const errorMessages = {
INTERNAL_SERVER_ERROR: {
message: "Internal server error!",
code: 500
},
ERROR_BODY_INVALID: {
message: "Invalid request body",
code: 400
}
};
Then throw an error like this
exports.handler = function(event, context, callback) {
try {
// do something
} catch (error) {
callback(JSON.stringify(errorMessages.INTERNAL_SERVER_ERROR));
};
}
When a lambda error regex matches then it's mapped to the configured response status code.
P.D. If you are using Java this method does not work and you need to use proxy integration
We are using S3 and Amazon API Gateway. I'm getting 502 errors when testing my API in AWS. On my local machine I always get the file as expected.
I created the following TestApiController which I make a simple HTTP GET request from a UI:
[HttpGet("file/{type}")]
public IActionResult GetFile(string type)
{
var filePath = _env.ContentRootPath + "/Files/my-small.fileType"; // ~5.5MB
if (type == "big"){
filePath = _env.ContentRootPath + "/Files/my-big.fileType";// ~6.6MB
}else if(type == "slowbig") {
Thread.Sleep(11000);
filePath = _env.ContentRootPath + "/Files/my-big.fileType";
}
var xml = System.IO.File.ReadAllText(filePath);
return File(Encoding.ASCII.GetBytes(xml), "text/xml", "hardcodedoutput.fileType");
}
In the test server AWS environment
if type == big OR type == slowbig
ERROR: HTTP 502. Response: {"message": "Internal server error"}
else
HTTP 200. I get the file hardcodedoutput.fileType as a download in my browser as expected.
On my Local development machine when running the API:
if type == big OR type == slowbig OR type == small
HTTP 200. I get the file hardcodedoutput.fileType as a download in my browser as expected.
A 502 can indicate a timeout issue. The server is taking longer than expected. Check the http server log for errors. If you see none, increase the timeout on the gateway.
According to the AWS docs:
AWS Lambda Limits
The following limits apply to function configuration, deployments, and
execution. They cannot be changed.
Invocation payload (request and response)
6 MB (synchronous)
256 KB (asynchronous)
This data (albeit a cryptic error) lines up perfectly w/ my experience. > 6MB files don't work.
The question is: Why is not possible to change http status before return responses in ViewerResponseEvents in lambda edge?
I have a Lambda function that must check every single response and change it's status code based on JSON file that I have in my lambda function. I deployed this lambda function in Viewer response because I want that this function executes before return every single response. Aws Documentation ( https://aws.amazon.com/blogs/networking-and-content-delivery/lambdaedge-design-best-practices/ ) says if you want to execute a function for all requests it should be placed in viewer events.
So, I've created a simple function that basically is cloning and changing the http status code of response before return it. I did this code for test:
exports.handler = async (event) => {
const request = event.Records[0].cf.request;
console.log(request);
console.log(`Original response`);
const response = event.Records[0].cf.response;
console.log(`Original response`);
console.log(response);
//clone response just for change the status code
let cloneResponseReturn = JSON.parse(JSON.stringify(response));
cloneResponseReturn.status = 404;
cloneResponseReturn.statusDescription = 'Not Found';
console.log('Log Clone Response Return');
console.log(cloneResponseReturn);
return cloneResponseReturn;
};
When I access the log in cloudwatch, it shows that response has http 404 code, but for some reason, cloudfront still returning the response with 200 status code. (I've cleared browsers cache, tested it in other tools such as postman, but in all of them CloudFront returns HTTP 200)
CloudWatch Log and Response print:
If I change this function to execute in origin response it will work, but I don't want to execute it ONLY in cache miss (+as aws tell us that origin events will be executed only in that case+). As origin events are executed only in cache miss, to execute that redirects I would have to create a chache header buster to make sure that origin events will be always executed.
Is really weird this behaviour of edge lambda. Does anyone have any idea how I can solve this? I already tried to clean cache of browsers and tools that I am using for test the requests, also clean the cache of my distribution but still not working.
I've posted the question in AWS Forum a week ago but it still without answer: https://forums.aws.amazon.com/message.jspa?messageID=885516#885516
Thanks in advance.