Error handling with aws-serverless-express

Viewed 549

I am using aws-serverless-express to provide an AWS Lambda handler for my Express webservice.

The Lambda works, however, I am not able to throw errors from Lambda. I tried to catch the whole serverless proxy with try/catch, but even when the application throws an error, it still goes into the succeed.

index.js

'use strict';
const awsServerlessExpress = require('aws-serverless-express');
const app = require('./dist/app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context, callback) => {
    try {
        context.callbackWaitsForEmptyEventLoop = false;
        context.succeed = (response) => {
            callback(null, response);
        };
        return awsServerlessExpress.proxy(server, event, context);
    } catch (e) {
        callback(e);
    }
};

I have an error handling middleware (used as the last), which works, but passing the error to the next() or re-throwing the error doesn't seem to trigger the catch in index.js.

errorHandler.js

const handleErrors = (err, req, res, next) => {

    res.setHeader('Content-Type', 'application/xml');
    res.status(200).send(DEFAULT_ERROR);
    next(err);
}

Does anyone know how to successfully throw an error from an Express application to be caught in the handler ?

0 Answers
Related