【问题标题】:Catch invalid request & return error with feathers-sequelize使用 feathers-sequelize 捕获无效请求并返回错误
【发布时间】:2017-03-17 15:10:49
【问题描述】:

我是 Feathers 的新手,我正在构建一个使用 feathers-cli 生成的 API。如果客户端执行了无效的 GET 请求:

例如。 http://localhost:3030/stations/?asdfasdf

它返回 500 错误:

ER_BAD_FIELD_ERROR: Unknown column 'stations.asdfasdf' in 'where clause'

我宁愿不向客户端报告这样的错误,而是希望返回“400 Bad Request”。我尝试使用hook.error 设置后挂钩,但这并没有捕捉到续集错误。

如何捕获错误并向客户端返回更安全、更通用的消息?

【问题讨论】:

标签: feathersjs feathers-sequelize


【解决方案1】:

error 钩子是一个单独的新钩子类型。使用 1.x feathers-cli 将您的 services index file 更改为类似

// Set up our before hooks
messageService.before(hooks.before);

// Set up our after hooks
messageService.after(hooks.after);

// Set up hooks
messageService.hooks(hooks);

然后在hooks/index.jsfile添加

exports.error = {
  all: [],
  find: [],
  get: [],
  create: [],
  update: [],
  patch: [],
  remove: []
};

您现在可以使用它来创建错误挂钩。对于你这样的情况:

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

exports.error = {
  all: [
    function(hook) {
      if(is(hook.error, 'ER_BAD_FIELD_ERROR')) { // Somehow check the Sequelize error type
        hook.error = new errors.BadRequest('Invalid query field');
      }
    }
  ],
  find: [],
  get: [],
  create: [],
  update: [],
  patch: [],
  remove: []
};

【讨论】:

  • 谢谢!我没有意识到当前版本中实现了错误挂钩。作为参考,我使用以下内容来获取错误代码:hook.error.original.code, 'ER_BAD_FIELD_ERROR'
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 2021-07-27
  • 2014-08-05
  • 1970-01-01
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多