简体   繁体   中英

How to Custom Error Object of Feathersjs?

Let say if I throw GeneralError when call a service, how to make error object like what I want:

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

I already try add this on error hook

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

But still cannot, and still return default error object of feathers:

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

All of the feathers errors can be provided with a custom message, which overrides the default message in the payload:

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

You can also pass additional data and/or errors. It's all documented: https://docs.feathersjs.com/api/errors.html

You can create your own custom error .

Example:

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());

As per @daff comment above, this is how you can customize the returned error object. Here includes extending built-in errors as well as a custom error

custom-errors.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 error like

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

Output (in Postman)

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

To return error from a hook you need to return Promise.reject

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

module.exports = function () {
  return async context => {
    if (yourtest) {
      return Promise.reject(new errors.NotAuthenticated('User authentication failed (0001)'));
    }
  };
};

This will give the response

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM