简体   繁体   中英

How to response error in feathersjs service to client?

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

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

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