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

huangapple go评论105阅读模式
英文:

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

问题

我已创建了一个API网关请求验证器来验证传入请求的主体。

我已使用 JsonSchemaVersion.DRAFT4 来创建我的模型。

验证器运行正常,但我收到的错误消息始终是"无效的请求主体",我希望能有一个更详细的消息。例如,确切的无效字段和可能的原因。

以下是我拥有的模型示例。

const CenterPointModel = {
  title: '中心点数据模型',
  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: '地图配置数据模型',
      type: JsonSchemaType.OBJECT,
      properties: {
        centerPoint: CenterPointModel,
        displayRangeMin: { type: JsonSchemaType.NUMBER },
        displayRangeMax: { type: JsonSchemaType.NUMBER },

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

      ]
    }
  });
};

我尝试在 enum: [GeometryType.Point] 下添加了 error: "类型必须为Point",但没有起作用。

我还发现了与模式和限制相关的答案,但这不是我要找的。我希望能够识别无效的字段,并在可能的情况下说明为什么无效。

英文:

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.

答案1

得分: 1

你可以修改400标准响应的映射模板:https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html

你可以将$context.error.validationErrorString信息添加到响应体中。

英文:

You can modify the mapping template of the standard response for 400: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html

You can add the $context.error.validationErrorString information into the response body.

答案2

得分: 0

我一直以错误的方式看待它。

JsonSchemaVersion.DRAFT4中,要查看错误消息,不是使用schema对象中的error属性,而是在主堆栈中创建一个新的GatewayResponse
以下代码适用于我:

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);
英文:

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);

huangapple
  • 本文由 发表于 2023年7月11日 02:55:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定