0

假设我在调用服务时抛出 GeneralError,如何制作我想要的错误对象:

{
"status": "Failed",
"code": "500_1",
"detail": "Something is wrong with your API"
} 

我已经尝试在错误钩子上添加这个

hook => {
hook.error = {
"status": "Failed",
"code": "500_1",
"detail": "Something is wrong with your API"
} 
return hook
}

但仍然不能,并且仍然返回羽毛的默认错误对象:

{
    "name": "GeneralError",
    "message": "Error",
    "code": 500,
    "className": "general-error",
    "data": {},
    "errors": {}
}
4

3 回答 3

1

您可以创建自己的自定义错误

例子:

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());
于 2020-10-06T14:46:28.627 回答
0

根据上面的@daff 评论,这是您可以自定义返回的错误对象的方式。这里包括扩展内置错误以及自定义错误

自定义错误.js

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

class CustomError extends FeathersError {
    constructor(message, name, code) {
        super(message, name, code);
    }

    toJSON() {
        return {
            status: "Failed",
            code: this.code,
            detail: this.message,
        }
    }
}

class BadRequest extends CustomError {
    constructor(message) {
        super(message, 'bad-request', 400);
    }
}

class NotAuthenticated extends CustomError {
    constructor(message) {
        super(message, 'not-authenticated', 401);
    }
}

class MyCustomError extends CustomError {
    constructor(message) {
        super(message, 'my-custom-error', 500_1);
    }
}

抛出错误,如

throw new MyCustomError('Something is wrong with your API');

输出(在邮递员中)

{
    "status": "Failed",
    "code": 500_1
    "detail": "Something is wrong with your API",
code
}
于 2020-12-15T11:44:55.470 回答
0

所有的羽毛错误都可以通过自定义消息提供,该消息会覆盖有效负载中的默认消息:

throw new GeneralError('The server is sleeping. Come back later.');

您还可以传递其他数据和/或错误。这一切都记录在案:https ://docs.feathersjs.com/api/errors.html

于 2019-11-02T18:29:00.477 回答