Return proper JSON validation errors from API Gateway Response

0

I'm working on developing a REST Api. I have created a model for one of my resources and am using it to validate a post request. I would like to return any validation errors as a properly formed JSON string.

I have a Gateway Response for Bad Request Body defined like this:

{
    "message": $context.error.messageString, 
    "errors":"$context.error.validationErrorString"
}

This works, but the issue I have is that what is returned by $context.error.validationErrorString is not a valid JSON string. If I submit the request with no information, the response returned returned is

{
  message: 'Invalid request body',
  errors: '[object has missing required properties (["contactEmail","contactMessage","contactName","contactReason","contactSubject"])]'
}

The string returned in the errors property is not valid JSON. If in my calling client I try to parse the error string has JSON it fails to parse.

So, my question is, is there a way with Gateway Responses to get the validation error string as a properly formed JSON string? If not, what is the recommended way to handle this? Why isn't this string a properly formed JSON string since it would seem that its intent is to be returned in a JSON response.

Incidentally, if it matters, this API end point is proxying to a Lambda function, but I want API Gateway to do the validation before the Lambda function is called.

adear11
已提问 2 年前289 查看次数
1 回答
1
已接受的回答

The $context.error.validationErrorString parameter is a string containing a detailed validation error message [1]. This may be proper JSON or not, depending on the validation errors.

Unfortunately, the customization of the validation error is currently not supported in API Gateway. There is also no current way to programmatically access the information obtained from "$context.error.validationErrorString" parameter within the API Gateway.

A workaround would be for the logic in the application or workflow (the client) that is responsible for processing the validation error message, will have to format the string as needed i.e stripping the parenthesis and square brackets from the $context.error.validationErrorString parameter response.

A feature request is open with regards to the format of the $context.error.validationErrorString parameter response not being a proper JSON string at all times. No timelines are available as to when this may be implemented.

Take care!

Resources:

[1] https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference

AWS
支持工程师
James_H
已回答 2 年前
profile pictureAWS
专家
Chris_G
已审核 2 年前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则