AWS response status is always 200

There is a task, which can't be avoided when developing serverless applicatoins on Amazon Web Services:

How to return a custom status code from a REST API?

One of the approaches is to use "prefix mapping", like for example is shown in this amazon blog post: Error Handling Patterns in Amazon API Gateway and AWS Lambda by Bryan Liston.

The only problem is that the approach doesn't always work. After a long debuggin session with many false tries, I've found the reason.

There is an AWS bug. More precisely, it is a feature because it is documented (Set up Data Mappings between Method and Integration)):

If you use '.+' as the selection pattern to filter responses, be aware that it may not match a response containing a newline ('\n') character.

Therefore, such a rule (from the referenced blog post) is wrong:

Selection pattern: “^[BadRequest].*”

The correct expression is:

Selection pattern: “^[BadRequest](\n|.)*”

The last question is: why the response message could contain newlines? Easily: they are produced by throwing an RuntimeException, and Java serializes the exception to a multi-line string.