0
votes

The issue

Using the Integration Response feature of AWS API Gateway, I can successfully handle errors thrown by Lambda. However, I'm having trouble mapping the Javascript error object to the mapping template. The error object looks like this.

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

Here's my Integration Response mapping for application/json

#set($errorMessage = $input.path('$.errorMessage'))
{
    "message" : $errorMessage
}

What I've tried

Using this configuration, this is the entire response returned to the client: Unexpected 'E'. This is one string and is not contained in a JSON object.

This E that's referenced in the error is the first character from my thrown error message, which is used to match the Lambda Error Regex. I know this as I briefly changed the first letter to X and I got Unexpected 'X' as the response.

When I change the first line of my mapping template to this (mapping the entire object rather than attempting to just map the errorMessage property)

#set($errorMessage = $input.path('$'))

I get only the stack trace from the Javascript error object.

{
    "message" : [
        "exports.handler (/var/task/index.js:9:11)"
    ]
}

This would suggest that either the entire response object being returned to API Gateway is just the stackTrace property from the Javascript error. But to me, this doesn't make sense as something is picking up the errorMessage as thats where the Unexpected 'E' message is coming from.

Similarly, when I try and map the errorType property, I get the same error as it also starts with E. I can only successfully map the message property when I use the entire $ input object, or just the stackTrace property.

What am I doing wrong here?

Other relevant code

Here's the API Gateway Error Model. The message property is clearly marked as a string type yet it only works when I return an array. Note: this is the default code

{
    "$schema" : "http://json-schema.org/draft-04/schema#",
    "title" : "Error Schema",
    "type" : "object",
    "properties" : {
        "message" : { "type" : "string" }
    }
}

Here's the Lambda function code

exports.handler = async (event, context, callback) => {
    throw new Error(Error: ABC123);
};
1

1 Answers

1
votes

I've figured it out. The solution is to use $input.json() rather than $input.path()

Here's my new mapping template

{
    "errorMessage" : $input.json('$.errorMessage')
}