I have a method on an API gateway which integrates with a Python Lambda function. I would like my API Gateway to return a 500 response if an exception is raised in my Python Lambda function where the errorMessage field doesn't match one of the regex's in the Integration Response's for the method.
I would only like to return a 200 if an exception is not raised and the lambda returns without failure.
With the setup in the picture above - any exception raised which does not match (.|\n)*'type':\s*'.*Error'(.|\n)*
for the 400 response will give a 200 response.
How can I return 500 if there is any exception raised which does not match an already configured response - while still returning 200 when the Python function returns successfully? Do I just have to wrap everything in my code (with try except) which could possibly raise an exception and generate a predictable errorMessage string?
EDIT:
I am currently 'achieving this' by having an Integration Response for 500 with a Lambda Error Regex of (.|\n)*
. Is this a reasonable way to catch unhandled exceptions as 500 errors?
EDIT:
It turns out this configuration is giving 500 errors when the Python function returns without Exception.
I would expect the Lambda Error Regex's to only attempt to match if an actual exception is raised by the Python function (as they only check the errorMessage field according to the documentation). Causing it to fall back on the default method of 201 (in the updated scenario). Oddly, it returns 400 when testing with the API GW console 'Test', but gives 500 (with the body mapping defined in the 500 Integration Response) when trying from anywhere else.
The only way I can think to return all unhandled exceptions as 500 is to raise Exception('Success')
instead of return
from my Python function - then have the 201 Lambda Error Regex match 'Success'... Which I'd really rather not do.
Your current approach is reasonable given the limitations of API Gateway's error response handling mechanism.
The API Gateway team has received feedback from multiple customers indicating the shortcomings of our error handling support. We are actively working on improving this and hope to deliver an improved error handling experience in the future.