【问题标题】:With loopback built-in methods, catch an error and return no error使用 loopback 内置方法,捕获错误并且不返回错误
【发布时间】:2017-09-21 17:53:03
【问题描述】:

我使用环回 3。 在我的客户端应用程序中,我使用 POST User 方法来创建一个新用户。如果电子邮件地址已存在于基础中,则服务器以状态 422 的错误响应。 我想捕捉这个错误,以便服务器返回 no error

我尝试像这样使用 afterRemoteError :

User.afterRemoteError('create', function(context, next) {
  if (context.error && context.error.statusCode === 422
      && context.error.message.indexOf('Email already exists') !== -1
      && context.req.body && context.error.message.indexOf(context.req.body.email) !== -1) {
    context.error = null;
    next(null);
  } else {
    next();
  }
});

但这不起作用,服务器仍然返回原始错误。如果我尝试用next(new Error('foo')) 替换next(null),那么服务器会返回新的错误,但我没有找到如何不返回错误。

【问题讨论】:

    标签: loopbackjs


    【解决方案1】:

    感谢我的同事找到了问题的解决方案!

    事实上,如果我们使用next(),afterRemoteError 会在中间件流程的后期触发。解决方案是使用明确的语法自行发送响应:

    User.afterRemoteError('create', function(context, next) {
        if (context.error && context.error.statusCode === 422
            && context.error.message.indexOf('Email already exists') !== -1
            && context.req.body && context.error.message.indexOf(context.req.body.email) !== -1)
        {
            context.res.status(200).json({foo: 'bar'});
        } else {
            next();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 2016-06-09
      • 2015-05-11
      • 2021-09-15
      相关资源
      最近更新 更多