machineghost
machineghost

Reputation: 35790

How can I make Feathers (Express-based API Framework) Return Error Responses

I've read the Feathers book, so I know that to create an error response I simply instantiate the appropriate feathers-errors class:

import {BadRequest} from 'feathers-errors';
const errorResponse = new BadRequest(`foo`, `bar`);

However, I'm having difficulty returning that error response to the user. Even when I create an endpoint that does nothing but return an error response ...

class SomeService {
    create(data) {
        return new BadRequest(`foo`, `bar`);
    }
}

it doesn't work: instead of getting an error response, I get no response, and inside the Chrome debugger I can see that the response is pending (until it eventually times out and becomes an ERR_EMPTY_RESPONSE).

I tried reading about Express error handling, and in the examples I saw people used next to wrap the the response. However, next comes from the error handler, and I'm not sure where in my Feathers code I can get that next function.

If anyone could help explain (using next or not) how I can return a complete, not pending, error response, I would greatly appreciate it.

Upvotes: 0

Views: 904

Answers (1)

Daff
Daff

Reputation: 44215

Your services have to return a promise. If your code is not asynchronous you can turn it into a promise with Promise.resolve and Promise.reject:

class SomeService {
    create(data) {
        return Promise.reject(new BadRequest(`foo`, `bar`));
    }
}

Also make sure you registered the Express error handler to get nicely formatted errors:

const errorHandler = require('feathers-errors/handler');

// Last in the chain
app.use(errorHandler);

There is also more information in the error handling chapter.

Upvotes: 2

Related Questions