【问题标题】:Identifying Mongoose schema validation errors as HTTP status codes将 Mongoose 模式验证错误识别为 HTTP 状态代码
【发布时间】:2018-10-26 14:10:00
【问题描述】:

我正在利用 Keystone.js 来提供轻量级的 CMS 和 API。我正在检查列表中的重复条目,如下所示:

Registration.schema.post('save', function(error, registration, next) {
  if (error && error.name === 'MongoError' && error.code === 11000) {
    error = Error(`409|${ registration['email'] } is already registered`);
  }

  next(error);
});

我正在从错误消息中解析状态代码以在我的 API 端点中返回。

是否有其他方法可以在 Keystone 管理中为重复项提供友好的错误消息并能够为 API 调用返回正确的状态代码?

【问题讨论】:

  • 你当前实现的消息是不是不够友好?
  • 它可以工作,但没有我想要的那么干净。
  • @Brandon 我给你发了一个例子。
  • 感谢@FrancisRodrigues。我会尽快检查一下。

标签: keystonejs


【解决方案1】:

作为数据库版本 v3.6.9

$ mongod --version
db version v3.6.9
git version: 167861a164723168adfaaa866f310cb94010428f
OpenSSL version: OpenSSL 1.0.1t  3 May 2016
allocator: tcmalloc
modules: none
build environment:
    distmod: debian81
    distarch: x86_64
    target_arch: x86_64

我认为您应该检查ValidationError 属性而不是MongoError,如下所示:

RegistrationSchema.create(obj)
  .then(...)
  .catch(err => console.error('[registration] output: ', err);

我们假设之前没有提到 email 来模拟 is required 错误。

你会看到这样的:

[registration] error:  { ValidationError: Registration validation failed: email: Path `email` is required.
at ValidationError.inspect (....)
errors: 
 {
   email:
     { Path `email` is required.
      ...
      message: 'Path `email` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'email',
        value: [],
        reason: undefined,
        '$isValidatorError': true } },
  _message: 'Registration validation failed',
  name: 'ValidationError' }

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 2017-01-02
    • 1970-01-01
    相关资源
    最近更新 更多