外部error handlingfunction
我有节点的应用程序,用户可以提供自己的function,并根据用户给我的一些URLpath我调用这个function,错误的情况下,问题的问题不会停止,所以我想以某种方式得到调用者的错误(如果有)在停止响应,在这种情况下logging做什么?
以免说这是用户提供的function,如果我们有目录中的文件,这工作正常
delete: function (req,res,Path) { var fileRelPath = 'C://'+ Path; fs.unlinkSync(Path); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end("File was deleted"); },
我从其他模块调用该函数来调用该函数
plugin[fnName](req, res, Path);
如果文件不存在,我得到错误,进程调用不停止…应该我可能检查上述调用代码后,如果res.end()被调用,如果不是明确结束,如果是如何检查它是否结束。
我的意思是这样的
plugin[fnName](req, res, Path); if(res.end was not invoked) res.end("error occurred" ) maybe to provide additional data somehow about the err ..
你可以尝试以下。 但function必须是同步的,就像你提供的例子。 否则try..catch
将无法正常工作。
var error; try{ plugin[fnName](req, res, Path); } catch(e){ error = e } if(!res.headerSent){ res.send(error); }
对于asynchronous操作,你必须用节点callback风格重写你的函数:
deleteAsync: function (req,res,Path,done) { var fileRelPath = 'C://'+ Path; fs.unlink(Path, function(err){ if(err) return done(err) res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end("File was deleted"); }); },
然后像这样打电话给他们:
plugin[fnNameAsync](req, res, Path,function(err){ if(err) res.send(err) });