Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS API Gateway error response generates 502 "Bad Gateway"

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
                }
              });
        }
    });
};
like image 736
johnny_mac Avatar asked Mar 17 '17 02:03

johnny_mac


People also ask

What causes 502 Bad gateway AWS?

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.

How do I fix 502 bad gateway in Alb?

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).

Is 502 Bad gateway permanent?

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.


1 Answers

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);
like image 144
Stefano Buliani Avatar answered Nov 19 '22 01:11

Stefano Buliani