Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10124

fs detect handle different error types

Over my nodejs application I have the following functions:

    const special_handle= function(err){
         console.error("Special Handled",err);
    }

    const normal_handle= function(err){
         console.error("Normal Handled",err);
    }

    const callback = function(err,mime,data){
       if(err) {
           if(/*file does not exist*/){
                 return special_handle(err);
           } else {
                  return normal_handle(err);
           }
       }
    }

    fs.readFile(fileFullPath,(err,data)=>{
        if(err){
           return callback(err);
        }

        const mimeType = mime.lookup(fileFullPath);
        callback(null,mimeType,data);
    });

What I want it when the file does not exist to do a special handling instead of do the normal one. But how I will know that the file does not exist over my callback?

Upvotes: 1

Views: 36

Answers (1)

Sven
Sven

Reputation: 5265

If the file/directory doesn't exist, you will get an ENOENT error. You can then use a switch or if clauses to handle different results.

A typical err object returned by a file/directory that doesn't exist will look like:

{ Error: ENOENT: no such file or directory, open 'test.js' errno: -2, code: 'ENOENT', syscall: 'open', path: 'test.js' }

So if you want to check whether the file exists, you could do:

if (err.code === 'ENOENT') {
  return special_handle(err)
} else {
  return normal_handle(err)
}

or if you want to check for multiple types of errors, such as EPERM which will be thrown when your program doesn't have permission to read the file/directory, you could use a switch-clause:

switch (err.code) {
  case 'ENOENT':
    return special_handle(err)
  case 'EPERM':
    return eperm_handle(err)
  case default:
    return normal_handle(err)
}

Upvotes: 1

Related Questions