2017-09-21 23 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(); 
    } 
});