Custom error classes in node
29 Jan 2016The Error class in Node.js provides the programmer with a reference point of failure when problems occur. To take this idea further, we can sub-class this class and specialize information within these errors to provide a richer execution tree in times of failure.
From the Node.js documentation:
A generic JavaScript
Error
object that does not denote any specific circumstance of why the error occurred.Error
objects capture a “stack trace” detailing the point in the code at which theError
was instantiated, and may provide a text description of the error.
In today’s post, I’ll walk through a deriving from the Error class and how you can use it in your client code.
Definition
We’ll be using the inherits
function from the util
module to accomplish sub-classification; as per usual. Our FooError
class looks like this:
For good measure, we’ll also define a BarError
:
That’s it as far as the definition is concerned. FooError
and BarError
are ready for us to use.
Usage
A bonehead example follows, but it’ll at least give you an example of what the logic tree looks like to investigate exactly what type of error just occurred.
We build an array of errors, enumerate the array; throw each error. In our catch
block, I’m simply console.log
the information out. We end up with the following:
Just by simply testing the name
property on these error objects, we can be a little more sophisticated in the way we make decisions on what to do:
This change results in the following being sent to the console: