php和nodeJs捕获异常在回掉函数中的差异
php代码:
try{ foo(2,function($param){ if($param==1){ throw new Exception('cathing'); } }); }catch(Exception $e){ echo $e->getMessage(); } function f1($v) { return $v + $v; } function foo($n, $f='') { if($n < 1) return; for($i=0; $i<$n; $i++) { echo $f ? $f($i) : $i; } } //运行结果cathing
nodeJs代码:
const fs = require('fs'); try { fs.readFile('/some/file/that/does-not-exist', (err, data) => { // mistaken assumption: throwing here... if (err) { throw err; } }); } catch (err) { // 这里不会截获回调函数中的throw console.error(err); } //运行结果如下图
结论:php在函数中可以捕获到异常,node不行。node可以用以下方式捕获,也就是错误信息优先的回调模式惯例。
const fs = require('fs'); function errorFirstCallback(err, data) { if (err) { console.error('There was an error', err); return; } console.log(data); } fs.readFile('/some/file/that/does-not-exist', errorFirstCallback);
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23