首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何自定义Feathersjs的错误对象?

如何自定义Feathersjs的错误对象?
EN

Stack Overflow用户
提问于 2019-11-02 13:41:18
回答 3查看 885关注 0票数 0

比方说,如果我在调用服务时抛出GeneralError,如何使error对象像我想要的那样:

代码语言:javascript
复制
{
"status": "Failed",
"code": "500_1",
"detail": "Something is wrong with your API"
} 

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

代码语言:javascript
复制
hook => {
hook.error = {
"status": "Failed",
"code": "500_1",
"detail": "Something is wrong with your API"
} 
return hook
}

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

代码语言:javascript
复制
{
    "name": "GeneralError",
    "message": "Error",
    "code": 500,
    "className": "general-error",
    "data": {},
    "errors": {}
}
EN

回答 3

Stack Overflow用户

发布于 2020-10-06 22:46:29

您可以创建自己的custom error

示例:

代码语言:javascript
复制
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());
票数 1
EN

Stack Overflow用户

发布于 2019-11-03 02:29:00

所有的羽化错误都可以与自定义消息一起提供,该消息覆盖有效负载中的默认消息:

代码语言:javascript
复制
throw new GeneralError('The server is sleeping. Come back later.');

您还可以传递额外的数据和/或错误。所有这些都有文档记录:https://docs.feathersjs.com/api/errors.html

票数 0
EN

Stack Overflow用户

发布于 2020-12-15 19:44:55

根据上面的@daff注释,这是定制返回的错误对象的方式。这里包括扩展内置错误和自定义错误

custom-errors.js

代码语言:javascript
复制
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);
    }
}

抛出错误,如

代码语言:javascript
复制
throw new MyCustomError('Something is wrong with your API');

输出(以Postman为单位)

代码语言:javascript
复制
{
    "status": "Failed",
    "code": 500_1
    "detail": "Something is wrong with your API",
code
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58668554

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档