I’ve created Stack, using AWS CDK, that extends cdk.Stack. In this stack I define lambda function to create product and define api gateway with method LambdaRestApi. Then I add request validator for this api, but I’m trying to get customised error message, if error occurs during body validation, not standard.
I define model of request:
const createProductModel = new apigateway.Model(
this,
"CreateProductModel",
{
restApi: api,
contentType: "application/json",
modelName: "CreateProductModel",
schema: {
type: apigateway.JsonSchemaType.OBJECT,
properties: {
title: { type: apigateway.JsonSchemaType.STRING, minLength: 1 },
description: { type: apigateway.JsonSchemaType.STRING },
price: { type: apigateway.JsonSchemaType.NUMBER, minimum: 0 },
count: { type: apigateway.JsonSchemaType.NUMBER, minimum: 1 },
},
required: ["title", "price", "description", "count"],
},
}
);
Define error template and model for error response
const errorResponseTemplate = JSON.stringify({
message: "$context.error.validationErrorString",
});
const errorResponseModel = new apigateway.Model(
this,
"ErrorResponseModel",
{
restApi: api,
contentType: "application/json",
modelName: "ErrorResponseModel",
schema: {
type: apigateway.JsonSchemaType.OBJECT,
properties: {
message: { type: apigateway.JsonSchemaType.STRING },
},
required: ["message"],
},
}
);
Define request validator
const requestValidator = new apigateway.RequestValidator(
this,
"CreateProductRequestValidator",
{
restApi: api,
validateRequestBody: true,
validateRequestParameters: false,
}
);
And then I’m trying to pass all these during adding method for resource. I pass errorResponseTemplate in integrationResponses option and I expected, that I get message that contains specified error
productsResource.addMethod(
"POST",
new apigateway.LambdaIntegration(createProductFunction, {
integrationResponses: [
{
selectionPattern: "(n|.)+",
statusCode: "400",
responseTemplates: { "application/json": errorResponseTemplate },
},
],
}),
{
requestValidator: requestValidator,
requestModels: {
"application/json": createProductModel,
},
methodResponses: [
{
statusCode: "400",
responseModels: {
"application/json": errorResponseModel,
},
},
{
statusCode: "201",
responseModels: {
"application/json": apigateway.Model.EMPTY_MODEL,
},
},
],
}
);
I expected, that I get custom message about error, for example “field price is required”, but I get message “Invalid request body”