AWS API Gateway: Regex for error is not picked up

情到浓时终转凉″ 提交于 2020-01-02 05:41:08

问题


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:

And in the integration response, I set the following:

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?


回答1:


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...



来源:https://stackoverflow.com/questions/47498940/aws-api-gateway-regex-for-error-is-not-picked-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!