2017-08-07 55 views
0

捕獲hapi請求生命週期中的所有錯誤。 我有一個註冊的處理程序,在HAPI中處理錯誤

public signup(request: Hapi.Request, reply: Hapi.Base_Reply) { 
    this.database.user.create(request.payload).then((user: any) => { 
     return reply({ 
      "success": true 
     }); 
    }).catch((err) => { 
     reply(Boom.conflict('User with the given details already exists')); 
    }); 
} 

現在,我趕上了錯誤,但我不能總是相信,我將只收到此錯誤信息。如果數據庫中有錯誤怎麼辦? 如何爲所有請求捕獲此類數據庫錯誤或任何其他未知錯誤。 ???

回答

0

也許你必須在你的答覆返回err.message

reply(Boom.conflig(err.message)) 

,或者如果你要管理或操作錯誤,您必須驗證錯誤的類型像

if (err instanceof DatabaseError) { 
    // manage database error 
} 
0

我想通在哈皮處理這種錯誤的方法。 我在找的是PreResponse處理程序。現在,PreResponse處理程序可以記錄所有錯誤,並且可以引發500錯誤響應。

我想說的是簡單地寫

reply(err) 

我可以送一個500錯誤,並且可以使用preResponse處理程序捕獲此錯誤。就像這樣,

server.ext('onPreResponse', (request: Hapi.Request, reply: Hapi.ReplyWithContinue) => { 
     const response = request.response; 
     if (!response.isBoom) { // if not error then continue :) 
      return reply.continue(); 
     } 
     console.log(response); 
     return reply(response); 
    }); 
+0

如果你只是想記錄錯誤,你可以使用'hapi-good'模塊https://github.com/hapijs/good – ivo