2017-08-07 54 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