How to response error in feathersjs service to client?

2.1k views Asked by At

I followed this link 'https://docs.feathersjs.com/services/readme.html' to create a restful service by feathersjs. It works fine for normal case. But I don't know how to response an error message to client, like 404, 500, etc. Below is the service code. It returns response via promise.resolve. How to return an error in this case?

class MessageService {
  get(id, params) {
    return Promise.resolve({
      id,
      read: false,
      text: `Feathers is great!`,
      createdAt: new Date.getTime()
    });
  }
}
1

There are 1 answers

0
notionquest On BEST ANSWER

You can use 'feathers-errors' module to set the error codes. Please see the sample code below.

const feathers = require('feathers');
const rest = require('feathers-rest');
const errors = require('feathers-errors');
const app = feathers();

app.configure(rest());
app.use('/messages', {
  get(id, params) {
    console.log(id);
    if (id === "1") {
      return Promise.resolve({
        id,
        read: false,
        text: `Feathers is great!`,
        createdAt: new Date().getTime()
      });
    } else if (id === "2") {  
      console.log(id);    
      var badRequest = new errors.BadRequest('http 400 bad request');
      return Promise.reject(badRequest);
    } else if (id === "3") {      
      console.log(id);    
      var generalError = new errors.GeneralError('Http 500 general error');
      return Promise.reject(generalError);
    }

  }
});

app.listen(3030);

feathers-errors module