php代码: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代码:node
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);