Search code examples
amazon-web-servicesaws-api-gatewayaws-cdk

How to create custom error messages for the invalid fields in API Gateway using CDK using schema version Draft4?


I have created an API Gateway requestValidator to validate the body of the incoming request.

I have used JsonSchemaVersion.DRAFT4 to create my models.

The validator works fine but the message the error message I receive is always "Invalid request body" and I wish to have a more informative message. Like which field exactly is invalid and the reason if possible.

Here is an example of the model I have.

const CenterPointModel = {
  title: 'CenterPoint Data Model',
  schema: JsonSchemaVersion.DRAFT4,
  type: JsonSchemaType.OBJECT,
  properties: {
    type: {
      type: JsonSchemaType.STRING,
      enum: [GeometryType.Point]
    },
    coordinates: { type: JsonSchemaType.ARRAY }
  },
  required: ['type', 'coordinates']
};

export const MapModel = (api: RestApi) => {
  return api.addModel('RequestBodyModel', {
    contentType: 'application/json',
    modelName: 'RequestBodyModel',
    schema: {
      schema: JsonSchemaVersion.DRAFT4,
      title: 'Map configuration Data Model',
      type: JsonSchemaType.OBJECT,
      properties: {
        centerPoint: CenterPointModel,
        displayRangeMin: { type: JsonSchemaType.NUMBER },
        displayRangeMax: { type: JsonSchemaType.NUMBER },

      },
      required: [
        'centerPoint',
        'displayRangeMin',
        'displayRangeMax',

      ]
    }
  });
};

I have tried out adding the error: "Type must be Point" under enum: [GeometryType.Point] but it didn't work.

I also found answers related to patterns and limit but this is not what I'm looking for.
I'm looking to identify the invalid field and if possible state why is it invalid.


Solution

  • I have been looking at it in the wrong way.

    In JsonSchemaVersion.DRAFT4 to view error messages, it is not done using the error attribute in the schema object but in the main stack create a new GatewayResponse The following code worked for me:

    const BadRequestBodyTemplate: string = JSON.stringify({
      message: '$context.error.validationErrorString'
    });
    
    const badReqBodyGatewayRespProps: GatewayResponseProps = {
              restApi: featuresApi,
              type: ResponseType.BAD_REQUEST_BODY,
              statusCode: HttpStatusCode.BadRequest,
              templates: {
                'application/json': BadRequestBodyTemplate
              }
            };
            new GatewayResponse(this, ApiGatewayResponses.BadRequestBody, badReqBodyGatewayRespProps);