修改sailsjs / nodejs错误对象

时间:2014-10-16 15:37:00

标签: node.js sails.js waterline

我已经在我的水线模型中粘贴了一个回调

为了给客户端一个漂亮的消息,我试图修改错误对象的状态,以便res.negotiate(err)将响应badRequest。但我的error.status = 400似乎被忽略了,当它传递给res.negotiate我仍然得到500错误返回(服务器错误而不是错误的请求)。

我正在处理这些文档

  

http://sailsjs.org/#/documentation/reference/res/res.negotiate.html   https://docs.nodejitsu.com/articles/errors/what-is-the-error-object   http://massalabs.com/dev/2013/10/17/handling-errors-in-nodejs.html

想法,错误?

beforeDestroy: function(criteria, next){
  var error = new Error('This shift has people scheduled and can not be deleted.');
  error.type = 'user';
  error.status = 400;
  return next(error);
}

此外,即使我收到服务器错误,也会返回消息。在这种情况下,在返回的错误对象上找不到“此班次有人安排......”我正在使用未经修改的响应页面,我不知道为什么它会被删除?

这是返回给客户端的错误对象。

error: "E_UNKNOWN"
raw: {}
status: 500
summary: "Encountered an unexpected error"

1 个答案:

答案 0 :(得分:0)

查看协商响应的来源,似乎应该返回400响应:

'node_modules\sails\lib\hooks\responses\defaults\negotiate.js'

 try {

    statusCode = err.status || 500;

    // Set the status
    // (should be taken care of by res.* methods, but this sets a default just in case)
    res.status(statusCode);

  } catch (e) {}

  // Respond using the appropriate custom response
  if (statusCode === 403) return res.forbidden(body);
  if (statusCode === 404) return res.notFound(body);
  if (statusCode >= 400 && statusCode < 500) return res.badRequest(body);

我建议在协商响应中设置一个断点,以验证它是否从beforeDestroy模型生命周期回调中调用。