2017-09-21 16 views
0

我使用Loopback 3. 在我的客户端应用程序中,我使用方法POST User创建新用户。如果电子邮件地址已经存在,则服务器响应状态为422的错误。 我想捕获此错误,以便服务器返回无错误使用回送内置方法,捕获错误并返回无错误

我试图用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),那么服务器返回新的错误,但我没有找到如何不返回任何错误。

回答

0

坦克给我的同事,找到解决问题的办法!

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