使用环回内置方法,捕获错误并且 return 没有错误

With loopback built-in methods, catch an error and return no error

我使用环回 3。 在我的客户端应用程序中,我使用方法 POST User 创建一个新用户。如果电子邮件地址已经存在于 basis 中,则服务器响应状态 422 的错误。 我想捕获这个错误,这样服务器 returns 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();
  }
});

但这不起作用,服务器仍然是 return 原来的错误。如果我尝试用 next(new Error('foo')) 替换 next(null) 然后服务器 returns 新错误,但我没有找到如何 return 没有错误。

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

事实是,如果我们使用 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();
    }
});