Reputation: 46
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": {}
}
Upvotes: 1
Views: 1858
Reputation: 126
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
Upvotes: 0
Reputation: 333
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
}
Upvotes: 1
Reputation: 11665
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());
Upvotes: 1
Reputation: 42666
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
Upvotes: 0