11

如何在操作钩子中返回错误?

用例是在保存新模型实例后发送推送通知。

我观察'after save'事件,发送推送。如果由于某种原因失败,我想发送一个500 response代码。我怎么做?

我无法找到关于该ctx对象实际是什么或包含什么的文档。

  Customer.observe('after save', function(ctx, next) {

  //model saved, but sending push failed for whatever reason, and I want to now send a 500 error back to the user
  //how?  what's inside ctx? how do you send back a response?  
  next();
});

谢谢

4

3 回答 3

12

我相信是这样的:

var error = new Error();
error.status = 500;
next(error);
于 2015-09-22T10:12:20.233 回答
9

扩展上一个答案,因为我还不能添加评论。

您可以通过以下方式为错误响应提供更多信息:

var error = new Error();
error.status = 401;
error.message = 'Authorization Required';
error.code = 'AUTHORIZATION_REQUIRED';

这将返回如下内容:

{
   "error": {
      "name": "Error",
      "status": 401,
      "message": "Authorization Required",
      "code": "AUTHORIZATION_REQUIRED",
      "stack": "Error: Authorization Required\n    at ..."
   }
}
于 2015-09-28T08:38:33.973 回答
0

关于ctx实际包含的内容有详细的文档。可以在Loopback after-save operation hook 文档中找到。

ctx 对象具有instance返回已保存模型实例的方法。您可以在检查模型实例后返回错误,如下所示:

if (ctx.instance) {
  // check if your push operation modified the instance
  // If condition is not met, throw the error
  var error = new Error()
  error.status = 500
  error.message = '...'
  next(error)
}

上面的文档涵盖了after save钩子的 ctx 对象的属性。

于 2017-12-04T13:51:11.537 回答