简体   繁体   中英

What is the error contract for functions from “fs” in Node?

In my app, written in JavaScript for Node, I wan't to try to recover from file system errors. In order to do that I need to know what that error can be. The manual doesn't say much. So my question is:

  • What is the contract for the error object? What can that error object be?

Example:

readFile('file/path', function (error, data) {
    if (error) throw error;
    console.log(data);
});

All errors returned are inherited from the JavaScript Error Object ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error ), and fall into two categories: JS errors and system errors.

Single operation APIs such as the readFile method in your example return either null, if there is no error, or an Error instance ( https://nodejs.org/api/errors.html ). Common system errors such as Permission Denied or No Such File can be returned, and an exhaustive list can be found here:

http://man7.org/linux/man-pages/man3/errno.3.html

There is plenty of documentation, you just need to be careful to catch the errors properly, especially when using async methods.

Errors are instances of the JS object and have properties. You can do something like:

    if (e.code === 'EISDIR') { 
        console.log("Is not a directory!"); 
    } else { 
        throw e; 
    }

Check out the docs here for the Node Error object.

Error

Typically it'll have a message and stack property. The message property is a detailed message about the error that was thrown. stack is the stack trace at the point when the error was thrown.

Some developers also put custom properties to add more details about the error. Hope this helps.

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