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 年前檢視次數 315 次
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 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南