错误

npm version Changelog

$ npm install @feathersjs/errors --save

feathersjs/errors 模块包含一组标准错误类,供所有其他Feathers模块使用,以及一个 Express错误处理程序 格式化那些 - 以及其他 - 错误并为REST调用设置正确的HTTP状态代码.

Feathers 错误

可以使用以下错误类型,它们都是 FeathersError 的实例:

小技巧

所有Feathers插件都会自动为您发出相应的Feathers错误.例如,大多数数据库适配器已经发送了来自ORM的验证错误的 ConflictUnprocessable 错误.

  • 400: BadRequest

  • 401: NotAuthenticated

  • 402: PaymentError

  • 403: Forbidden

  • 404: NotFound

  • 405: MethodNotAllowed

  • 406: NotAcceptable

  • 408: Timeout

  • 409: Conflict

  • 411: LengthRequired

  • 422: Unprocessable

  • 429: TooManyRequests

  • 500: GeneralError

  • 501: NotImplemented

  • 502: BadGateway

  • 503: Unavailable

Feathers错误包含以下字段:

  • name - 错误名称(例如 “BadRequest”, “ValidationError” 等)

  • message - 错误消息字符串

  • code - HTTP状态代码

  • className - 一个CSS类名,可以根据错误类型设置样式错误. (例如  “bad-request” 等)

  • data - 包含传递给Feathers错误的任何对象的对象,除了 errors 对象.

  • errors - 包含任何内容的对象传递给 errors 中的Feathers错误.这通常是验证错误,或者您想要将多个错误组合在一起.

小技巧

要将Feathers错误转换回对象,请调用 error.toJSON(). JavaScript Error对象的正常 console.log 不会自动显示上面描述的那些附加属性(即使它们可以直接访问).

自定义错误

您可以通过从 FeathersError 类扩展并使用 ``(msg,name,code,className,data)` 来调用其构造函数来创建自定义错误.:

  • message - 错误消息

  • name - 错误名称(如 my-error)

  • code - An HTTP error code

  • className - 错误类的全名

  • data - 要包含在错误中的其他数据

const { FeathersError } = require('@feathersjs/errors');

class UnsupportedMediaType extends FeathersError {
  constructor(message, data) {
    super(message, 'unsupported-media-type', 415, 'UnsupportedMediaType', data);
  }
}

const error = new UnsupportedMediaType('Not supported');

console.log(error.toJSON());

例子

您可以使用以下几种方法:

const errors = require('@feathersjs/errors');

// If you were to create an error yourself.
const notFound = new errors.NotFound('User does not exist');

// You can wrap existing errors
const existing = new errors.GeneralError(new Error('I exist'));

// You can also pass additional data
const data = new errors.BadRequest('Invalid email', {
  email: 'sergey@google.com'
});

// You can also pass additional data without a message
const dataWithoutMessage = new errors.BadRequest({
  email: 'sergey@google.com'
});

// If you need to pass multiple errors
const validationErrors = new errors.BadRequest('Invalid Parameters', {
  errors: { email: 'Email already taken' }
});

// You can also omit the error message and we'll put in a default one for you
const validationErrors = new errors.BadRequest({
  errors: {
    email: 'Invalid Email'
  }
});

服务器端错误

如果您忘记添加 catch() 语句,则承诺吞下错误.因此,你应该确保你**总是**在你的承诺上调用 .catch().要在全局级别捕获未捕获的错误,您可以将以下代码添加到最顶层的文件中.

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise ', p, ' reason: ', reason);
});

错误处理

确保在返回客户端之前清除错误非常重要. 快速错误处理middlware 仅适用于REST调用.如果你想确保也处理ws错误,你需要使用 App Hooks. App Error Hooks会在每次服务调用时调用错误,无论传输如何.

这是一个示例错误处理程序,您可以添加到app.hooks错误.

const errors = require("@feathersjs/errors");
const errorHandler = ctx => {
  if (ctx.error) {
    const error = ctx.error;
    if (!error.code) {
      const newError = new errors.GeneralError("server error");
      ctx.error = newError;
      return ctx;
    }
    if (error.code === 404 || process.env.NODE_ENV === "production") {
      error.stack = null;
    }
    return ctx;
  }
};

然后将它添加到error.all钩子

module.exports = {
  //...
  error: {
    all: [errorHandler],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
};