Skip to content

Handling

Thomas Ruiz edited this page Oct 28, 2018 · 5 revisions

Handling

The handle function

handle(next: Function, shouldThrowOnUnhandled: boolean) should be the entry point of all your lambdas. It will handle any kind of event from AWS.

Handle takes 2 parameters: next, which is your controller function, and shouldThrowOnUnhandled that decides what to do when an unhandled event happens.

API Gateway

JSON

Request and response body are automatically JSON encoded.

If the request body is invalid, it will return a HTTP 400 Bad Request response.

HTTP Status Code

POST requests always get a 201 status code when no error happened. All other requests are either 200 or 204, depending on whether the body is empty or not.

In case of errors, see below.

Error handling

All errors are caught by the handle function. The type of the errors is defined by the name property on the error thrown.

If you throw an error in your controller, you can specify the HTTP status code by following this structure:

throw {
  statusCode: number,
  body: any,
};

If the error is a ValidationError, the HTTP status code returned is a 422. The error will have the following structure:

{
    "data": [
        {
            "message": "\"email\" is required",
            "path": [
                "email"
            ],
            "type": "any.required",
            "context": {
                "key": "email",
                "label": "email"
            }
        }
    ]
}

The data entries are the error messages returned by Joi. See Validation for more info.

Example

export const handler = handle(async (event: APIGatewayEvent): Promise<string> => {
  return 'hello world';
});
Clone this wiki locally