6

I have a Lambda function tied to the AWS API gateway. When I call it with something like /foo/bar and bar does not exist, my function returns (correctly) something like:

{
  "code": 404,
  "message": "bar not found"
}

I now want the status code of this to be 404, too, but following the tutorials I could find on the net, I had no success so far. What I did:

I created a method response for 404 that looks like this: 404 response

And in the integration response, I set the following: 404 integration response

To my understanding, this should set the code to 404 when 404 appears in the response document, but I still get 200.

What am I missing?

2
  • stackoverflow.com/a/47105287/6108211 I hope it helps Commented Nov 30, 2017 at 12:15
  • No, it didn't. I even tried to shape the output so it looks exactly like yours, and I still get 200. It seems that it doesn't pick up the regex. If I set the regex to .* (match all), it works, but as soon as I incorporate any other character, it is ignored. Commented Dec 3, 2017 at 13:59

1 Answer 1

8

I investigated some more and found out that the API gateway is very picky about where it expects its error messages, and how I have to get them out.

It is deeply buried and not easily found in the documentation that the errorMessage property is considered for matching against the Lambda Error Regex, and the first answer to this post states you have to throw an exception when using Java 8. I use .net for my Lambda function, so I did this very simple thing:

new Exception("404") |> raise

then I set up the Lambda Error Regex 404 and it worked.

Next thing I tried was:

new Exception("foo 404 bar") |> raise

With the regex .*404.* it still worked.

Now comes the thing: I tried to emit a JSON object as the error, but I found nothing in C# or F# to let me do this, so I came up with the following:

type Error = {
    code: int
    message: string
}

...

new Exception({ code = 404; message = name |> sprintf "%s not found" } |> JsonConvert.SerializeObject) |> raise

And boom, I got 200 again.

So I conclude from this, AWS doesn't like stringified JSON in the errorMessage property, so I now just output a simple string like this:

new Exception(name |> sprintf "404: %s not found") |> raise

and using the regex 404:.*, it now works. That means, I somehow have to construct my desired output object using the mappings in the API gateway.

This is quite inconvenient and something easy to trip over...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.