如何在对客户端的feathersjs服务中响应错误?

时间:2016-12-28 06:54:33

标签: node.js feathersjs

我点了这个链接'https://docs.feathersjs.com/services/readme.html'来创建featherjs的宁静服务。它适用于正常情况。但我不知道如何向客户端回复错误消息,如404,500等。以下是服务代码。它通过promise.resolve返回响应。在这种情况下如何返回错误?

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

1 个答案:

答案 0 :(得分:1)

您可以使用 'feathers-errors' 模块设置错误代码。请参阅下面的示例代码。

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