我正在使用HapiJS开发RESTful API。
我正在使用HapiJS v17来利用async / await。
我的意图是不处理每条路线中的异常,而要集中处理所有 unhandledRejection 。
我试图实现这一目标的方法是在服务器启动时尽早收听$colors = [
'#ff0000',
'#e50000',
'#cc0000',
];
foreach ($colors as $hex){
list($redHex,$greenHex,$blueHex) = str_split(trim($hex,'#'),2);
$redVal = hexdec($redHex);
$greenVal = hexdec($greenHex);
$blueVal = hexdec($blueHex);
if($redVal > $greenVal+$blueVal){
echo $hex.' is most likely red';
}
}
事件。
unhandledRejection
然后,例如,在我的业务逻辑代码中,我有意不捕捉拒绝的承诺(例如数据库错误),希望我能够在process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
});
的回调中对其进行处理
但是process.on('unhandledRejection'
语句永远不会触发。
例如:
console.log
handler: async (request, h) => {
const user = request.user;
const userIdToUpdate = request.params.id;
const firstName = request.payload.firstName;
const lastName = request.payload.lastName;
const roles = request.payload.roles;
const updatedUser = await UserCtrl.updateUser(userIdToUpdate, firstName, lastName, roles, user.tenantId.toString());
const response = h.response(updatedUser.sanitize());
response.type('application/json');
return response;
}
返回一个Promise,比如说数据库连接已断开,我假设应该拒绝Promise,但是为什么UserCtrl.updateUser
没有被触发?
答案 0 :(得分:1)
我认为HapiJS捕获了您的请求处理程序的错误。
查看代码-似乎错误catched there。
不确定以何种格式以及在什么条件下将其进一步抛出。
我还是不会依赖于这种逻辑的框架,至少要用自己的包装器包装所有处理程序并在其中记录所有错误。
答案 1 :(得分:0)
我最终实现了一个 PreResponse 钩子,该钩子将检查响应是否为错误并采取相应措施
#Input
Sl No TESTER MP A1 B1 C1
1 435 A 4.96 6.75 4
1 435 B 10.87 83.86 4.19
1 435 C 12.83 126.38 1.01
1 435 D 12.9 129.22 3.63
1 435 E 10.64 74.41 4.25
2 435 A 4.96 7.43 2.43
2 435 B 10.94 84.53 3.43
2 435 C 12.84 126.55 2.57
2 435 D 12.9 128.95 2.1
2 435 E 10.6 74.23 5.04
#Output Required
Sl Test A B C D E A B C D E A B C D E
1 435 4.96 10.87 12.83 12.9 10.64 6.75 83.86 126.38 129.22 74.41 4.00 4.19 1.01 3.63 4.25
2 435 4.96 10.94 12.84 12.9 10.6 7.43 84.53 126.55 128.95 74.23 2.43 3.43 2.57 2.10 5.04