dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.71k stars 164 forks source link

Catch-all error handling with API GW? #298

Closed 0xPT closed 4 months ago

0xPT commented 4 months ago

Hi,

I'm running into a problem where my app.use(errorHandler) isn't catching any of the thrown errors. From what I've read online (https://stackoverflow.com/questions/56429705/send-custom-error-message-with-serverless-http-express) and (https://stackoverflow.com/questions/46689554/whats-the-correct-way-of-returning-http-error-codes-in-serverless-lambda/46697547#46697547), it seems like it may be due to the way API Gateway handles errors.

Here's an example of my code.

app.use('/route', exampleRoutes)

app.use(Sentry.Handlers.errorHandler());

app.use(errorHandler)

const handler = serverless(app, { provider: 'aws' });

exports.handler = async (
  event: APIGatewayEvent
  context: Context
) => {
  try {
      const result = await handler(event, context);
      return result;
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'this is an error' }),
    };
  }
};

You can see that even in the handler export I'm trying to return a 500 as a test and even that doesn't come through. The only error I ever get from the backend is Error: {"status":502,"body":"{\"message\": \"Internal server error\"}"} whenever I throw an error from "exampleRoutes".