4

I'd like to send custom error types back from my lambda function. How can I control what shows up in the errorType property so the error that gets returned to my api gateway?

 var err = new Error('foo');
 context.fail(err);

returns

{
  "errorMessage": "foo",
  "errorType": "Error",
  "stackTrace": [
    "exports.handler (/var/task/index.js:11:19)"
  ]
}

I'd like to manipulate it so that the errorType in the response can be something like "InvalidParam".

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460
  • Did you figure this out? I'm not sure you can return an error object from lambda to the API gateway and also be able to map a HTTP Status Code to it. – ac360 Jul 12 '15 at 20:01
  • based on looking around it looks like you can't set custom error types - you have to set the error string and just map error types based on the strings, e.g. http://stackoverflow.com/questions/31329495/is-there-a-way-to-change-the-http-status-codes-amazon-api-gateway-returns/31371862#31371862 – MonkeyBonkey Jul 13 '15 at 21:32
  • I've written a [blog post on this topic](http://www.jayway.com/2015/11/07/error-handling-in-api-gateway-and-aws-lambda/) and I hope to have a discussion with Amazon regarding this in a near future. – Carl Nov 10 '15 at 10:25

2 Answers2

5

The returned errorType represents the 'name' property set on the error.

So the following code:

var error = new Error('Its an error!');
error.name = 'TheName';

context.fail(error);

Results in the following response from Lambda to API Gateway:

{
  "errorMessage": "Its an error!",
  "errorType": "TheName",
  "stackTrace": [
    "exports.handler (/var/task/index.js:10:21)"
  ]
}

Unfortunately, it seems the API Gateway only matches the Error Regex to the 'errorMessage' property. At least based on my attempts and what I've read so-far. So setting the error type won't help if you are trying to map to status codes. (as mentioned in the comments)

One way to get a little bit of both worlds is to "toString()" your error when calling context.fail. This will format your error message as "[name]:[error message]".

You can then match your API Gateway Error Regex to the specific error "name" property.

So calling:

var error = new Error('Its an error!');
error.name = 'TheName';

context.fail(error.toString());

When API Gateway Regex mapped to status 500:

TheName.*

Results in the following status 500 API Gateway response:

{
  "errorMessage": "TheName: Its an error!"
}
Michael Goin
  • 416
  • 6
  • 11
0

Error mapping on Lambda responses was recently extended to provide 4xx status codes back to the client, and we're continuing to improve this feature.

Michael's answer is a good one to send the name back along with the message.

jackko
  • 6,998
  • 26
  • 38