简体   繁体   中英

Warp function outside with error handling

I've node application which users can provide own function and according to some URL path which the user give I invoke this function,the problem in case of error the request doesnt stops so I want somehow to get the error in the caller (if any) in stops the response,what is recorded to do in this case ?

lest say that this is the function which the user provided,in case we have the file in the directory this is working fine

delete: function (req,res,Path) {

    var fileRelPath = 'C://'+ Path;
    fs.unlinkSync(Path);
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end("File was deleted");
},

I call to this function from other module to invoke the function

plugin[fnName](req, res, Path);

In case the file doesn't exist I got error and the process call not stops... should I maybe check somehow after the above invoke code if res.end() was called,if not to end it explicit,if yes how to check if it ended.

I mean something like

plugin[fnName](req, res, Path);
if(res.end was not invoked)
res.end("error occurred"  )
maybe to provide additional data somehow about the err ..

You can try the following. But The function has to be synchronous, like the example you provided. Otherwise try..catch won't work.

var error;
try{
  plugin[fnName](req, res, Path);
}
catch(e){
  error = e
}

if(!res.headerSent){
  res.send(error);
}

For Async operations you have to rewrite your function in node callback style:

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


},

then call them like this:

plugin[fnNameAsync](req, res, Path,function(err){
  if(err)
     res.send(err)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM