简体   繁体   中英

Can some one explain what are the error codes in nodejs (not status codes)

This question I faced in my Interviews many times, but still I can't find the answer for this. I already googled it, but did not find the exact answer for this. Pls anybody let me know the exact answer for this.

Question: What are Error Codes in NodeJs?

I answered the error status codes. But the Interviewer said that, am not asking status codes. Pls explain the answer. Thank you in advance.

You are facing this question because error code was introduced in node 8.x previous to 8 there was error message in Error class which caused issues in very basic things due to which developers was forced to create custom classes for Error. Refer https://nodejs.org/docs/latest-v7.x/api/errors.html#errors_class_error

Later in Node 8, Error Codes are introduced in node 8.x to all of the error objects thrown by the Node.js APIs https://nodejs.org/api/errors.html#errors_class_error

Node Error Codes: https://nodejs.org/dist/latest/docs/api/errors.html#errors_node_js_error_codes

Why you should use error codes?

Till Node7, most of the Errors thrown by Node.js only had a message associated with them. If you wanted to have your code take a specific action based on the Error, you would have had to compare the message string to a known value. The result might be something like:

try {
// Do something
}
catch(error) {
    if (error.message == 'a simpe error'){
        // do something
    }
    else {
        // do something
    }
}

This is not good practice as in most cases when you get an error from Node.js it's more likely that your code will simply log/display the message and then branch to a common recovery path.

Now you might have noticed that there is a typo in the message comparison used in the example above. Well, that can happen with the Node.js code base as well or there are possibilities that node redefine the message strings.

The hard dependency on the message string also poses a challenge for internationalization.

This should allow the earlier example to be re-written as follows:

try {
    // Do something
}
catch(error) {
    if (error.code == 'A_ERROR_CODE'){
        // do something
    }
    else {
        // do something
    }
}

Using above practice will ensure that if/when the message changes in the future, the code won't be affected as the error code remains unchanged.

Yes error codes & status codes are different things. Error codes are whenever we have any ever in node like

try{} catch(error){ error.code }

these are error codes. For more detail kindly check this blog on medium Medium Blog

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