模型上的 Loopback 4 自定义错误消息

Loopback 4 custom error messages on models

根据 Loopback 4 documentation,您可以在模型验证时添加自定义错误消息,如下所示:

jsonSchema: {
  maxLength: 30,
  minLength: 10,
  errorMessage:
    'name must be at least 10 characters and maximum 30 characters',
},

我想以这种方式生成自定义错误消息,但我只收到给定验证的默认错误消息。这是我的代码:

jsonSchema: {
    maxLength: 13,
    errorMessage: "Primary phone number is required and should be formatted like (XXX) XXX-XXXX",
    pattern: "[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}",
  },

})

当我给它一个像“123 456-789”这样的字符串时,我得到这个:

{ "error": { "statusCode": 422, "name": "UnprocessableEntityError", "message": "The request body is invalid. See error object details property for more info.", "code": "VALIDATION_FAILED", "details": [ { "path": "/primary_phone", "code": "pattern", "message": "should match pattern \"[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}\"", "info": { "pattern": "[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}" } } ] } }

我已经为 errorMessage 尝试了多种放置方式并尝试了拼写,但没有任何改变我得到的错误。我还需要做些什么才能显示这些自定义错误消息吗?

Loopback 成员 Hage Yaapa 告诉我这是一个错误文档的案例。缺少的部分是:

this.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS).to({
  validation: {
    ajvKeywords: true,
    ajvErrors: true
  }
});

必须将此添加到您的 application/context 才能启用针对自定义错误的额外功能。