Return 错误与自定义错误对象格式

Return errors with custom error object format

我正在尝试定义我自己的错误格式以在响应中返回。 我自己写了中间件:

function catchAndLogErrors(app) {
    return function (err, req, res, next) {
       // stuff happening...
       throw new Error(err.message, {name: err.name, code: err.code, className: err.className, info: err.info, data: err.data});
    };
}

然后在 /src/middleware/index.js 中我注释掉了 handler 并放置了我自己的中间件:

const handler = require('feathers-errors/handler');
const catchAndLogErrors = require('my-middleware');
...

app.use(catchAndLogErrors(app));
// app.use(handler());

但我得到返回的错误 HTML,它实际上只是消息和堆栈跟踪,但 none 其他属性。

有什么想法吗?

由于您注释掉了 Feathers error handler you will have to implement your own Express error handler 格式错误并发送类似于此的响应(而不是仅仅抛出它)(如果您想发送 JSON):

function catchAndLogErrors(app) {
    return function (err, req, res, next) {
      res.json(err);
    };
}

Feathers 修改服务方法调用错误的真正方法是error hooks. They allow you to modify hook.error to the response you need, e.g. with an application wide hook,适用于所有服务调用:

app.hooks({
  error(hook) {
    const err = hook.error;

    //change `hook.error` to the modified error    
    hook.error = new Error(err.message, {
      name: err.name,
      code: err.code,
      className: err.className,
      info: err.info,
      data: err.dat
    });
  }
});