有错误处理的外部扭曲函数

Warp function outside with error handling

本文关键字:函数 外部 处理 有错误      更新时间:2023-09-26

我有节点应用程序,用户可以提供自己的功能,并根据用户给出的URL路径调用此函数,在错误的情况下,请求不会停止,所以我想以某种方式在调用者(如果有的话)中获得错误停止响应,在这种情况下记录要做什么?

不要说这是用户提供的函数,以防我们在目录中有文件这很好

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 ..

您可以尝试以下操作。但是函数必须是同步的,就像您提供的示例一样。否则try..catch将无法工作。

var error;
try{
  plugin[fnName](req, res, Path);
}
catch(e){
  error = e
}
if(!res.headerSent){
  res.send(error);
}

对于异步操作,你必须重写你的函数在节点回调风格:

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)
});