php代码:try{foo(2,function($param){if($param==1){thrownewException('cathing');}});}catch(Exception$e){echo$e->getMessage();}functionf1($v){return$v+$v;}functionfoo($n,$f=''){if($n<1)返回;for($i=0;$i<$n;$i++){echo$f?$f($i):$i;}}//运行结果cathingnodeJscode:constfs=require('fs');try{fs.readFile('/some/file/that/does-not-exist',(err,data)=>{//错误的假设:throwinghere...if(err){throwerr;}});}catch(err){//throw在回调函数这里不会被拦截console.error(err);}//运行结果如下图结论:php可以捕获函数中的异常,node不行。Node可以通过以下方式被捕获,这是错误信息优先回调的方式约定。constfs=require('fs');functionerrorFirstCallback(err,data){if(err){console.error('有错误',err);返回;}console.log(数据);}fs。readFile('/some/file/that/does-not-exist',errorFirstCallback);
