Hướng dẫn custom error javascript
When we develop something, we often need our own error classes to reflect specific things that may go wrong in our tasks. For errors in network operations we may need Our errors should support basic error properties like JavaScript allows to use As the application grows, our own errors naturally form a hierarchy. For instance, Extending ErrorAs an example, let’s consider a function Here’s an example of how a valid
Internally, we’ll use Our function Our The
Now let’s inherit
Please
note: in the line The parent constructor also sets the Let’s try to use it in
The
Please take a look at how we use We could also look at
The Also it’s important that if Further inheritanceThe
The new class Please note that Let’s call it Here’s the code with
Now custom errors are much shorter, especially Wrapping exceptionsThe purpose of the function The code which calls The scheme is like this:
In the code above we can see two types of errors, but there can be more. If the Often the answer is “No”: we’d like to be “one level above all that”. We just want to know if there was a “data reading error” – why exactly it happened is often irrelevant (the error message describes it). Or, even better, we’d like to have a way to get the error details, but only if we need to. The technique that we describe here is called “wrapping exceptions”.
Then the code that calls Here’s the code that defines
In the code above, So the outer code checks The approach is called “wrapping exceptions”, because we take “low level” exceptions and “wrap” them into Summary
|