I have an API Gateway with a LAMBDA_PROXY Integration Request Type. Upon calling context.succeed
in the Lambda, the response header is sent back with code 302
as expected (shown below). However, I want to handle 500
and 404
errors, and the only thing I am sure about so far, is that I am returning the error incorrectly as I am getting 502 Bad Gateway
. What is wrong with my context.fail
?
Here is my handler.js
const handler = (event, context) => {
//event consists of hard coded values right now
getUrl(event.queryStringParameters)
.then((result) => {
const parsed = JSON.parse(result);
let url;
//handle error message returned in response
if (parsed.error) {
let error = {
statusCode: 404,
body: new Error(parsed.error)
}
return context.fail(error);
} else {
url = parsed.source || parsed.picture;
return context.succeed({
statusCode: 302,
headers: {
Location : url
}
});
}
});
};
HTTP 502 (bad gateway) errors can occur for one of the following reasons: The web server or associated backend application servers running on EC2 instances return a message that can't be parsed by your Classic Load Balancer.
A few common reasons for an AWS Load Balancer 502 Bad Gateway: Be sure to have your public subnets (that your ALB is targeting) are set to auto-assign a public IP (so that instances deployed are auto-assigned a public IP).
Fix 1: Refresh the PageMany server errors are only temporary, not permanent, and 502 bad gateway is no exception. If you're getting this error, the first thing you should do is refresh the page after a couple of minutes and see if the website loads up again.
If you throw an exception within the Lambda function (or context.fail), API Gateway reads it as if something had gone wrong with your backend and returns 502. If this is a runtime exception you expect and want to return a 500/404, use the context.succeed method with the status code you want and message:
if (parsed.error) {
let error = {
statusCode: 404,
headers: { "Content-Type": "text/plain" } // not sure here
body: new Error(parsed.error)
}
return context.succeed(error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With