【问题标题】:Strongloop: how do you return an error if Operation Hook fails?Strongloop:如果 Hook 操作失败,如何返回错误?
【发布时间】:2015-08-11 20:45:40
【问题描述】:

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

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

我观察到'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();
});

谢谢

【问题讨论】:

  • 您可以使用console.log(ctx) 检查 ctx 对象。它是表示请求和相关数据的上下文对象(例如,ctx.instance 是您的 Customer 实例)。要通过操作钩子传递错误,请将错误通过next(error); 作为钩子的最后一行传递。但这就是我的理解结束的地方——我不确定这会在哪里结束,或者如何在中心位置处理它。
  • 您可以使用 assert 模块以干净的方式抛出错误。

标签: strongloop loopback


【解决方案1】:

我认为是这样的:

var error = new Error();
error.status = 500;
next(error);

【讨论】:

  • next(err) 返回正确的对象,但用“未处理的错误”污染了我的日志。我认为没有throw error 它不应该打印那个。我该怎么办?谢谢
【解决方案2】:

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

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

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 ..."
   }
}

【讨论】:

    【解决方案3】:

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

    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 对象的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 2014-09-26
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多