简体   繁体   中英

NodeJS error handling - using error codes or subclassing

What are proc and cons of using custom error codes versus using custom subclasses of Error in NodeJS?

In a language like Java or Python I would use subclasses because I could handle it within different catch blocks. However, in JavaScript writing a specific subclass of Error for each precise error case looks redundant for me as far as you can't utilize it by catch block without using the instanceof operator. By the way, throw isn't a usual way to pass an error in NodeJS too (I mean error-first callbacks style). So, eventually, I decided to stick with one custom class (inherited from Error ) for all project's errors. However, now I should introduce a lot of different error codes. And I'm wondering - is it a regular flow to deal with errors in NodeJS?

Creating an Error object for your error messages allows you to specify additional things that might be relevant to the error itself. Consider the following:

var e = new Error("An error message");
e.status = "TERMINATED";
e.exit_code = 127:

The Error object is just another javascript object so adding properties to it is valid. Additionally, you also have some useful things to track your error messages such as "e.stack" to see how the stack looked like when the error object was created. For additional properties of the Error object, refer to this website .

Why don't you create an Error Factory "class" that creates Error objects with the added "error code" that you need? You can always check if the Error you catch was created by the factory if it has any of the properties you augment the object with.

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