Skip to content

Commit

Permalink
docs: re-word clarification about setErrorHandler() (#5269)
Browse files Browse the repository at this point in the history
Signed-off-by: codershiba <155646804+codershiba@users.noreply.github.com>
  • Loading branch information
codershiba committed Jan 21, 2024
1 parent 79042e6 commit cf6a87b
Showing 1 changed file with 15 additions and 21 deletions.
36 changes: 15 additions & 21 deletions docs/Reference/Errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,21 @@ Some things to consider in your custom error handler:
internally monitors the error invocation to avoid infinite loops for errors
thrown in the reply phases of the lifecycle. (those after the route handler)

**Important**: When utilizing Fastify's custom error handling through
[`setErrorHandler`](./Server.md#seterrorhandler),
it's crucial to be aware of how errors
are propagated between custom and default error handlers.
When utilizing Fastify's custom error handling through [`setErrorHandler`](./Server.md#seterrorhandler),
you should be aware of how errors are propagated between custom and default
error handlers.

If a plugin's error handler re-throws an error, and the error is not an
instance of [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
(as seen in the `/bad` route in the following example), it will not propagate
to the parent context error handler. Instead, it will be caught by the default
error handler.

To ensure consistent error handling, it is recommended to throw instances of
`Error`. For instance, in the following example, replacing `throw 'foo'` with
`throw new Error('foo')` in the `/bad` route ensures that errors propagate through
the custom error handling chain as intended. This practice helps avoid potential
pitfalls when working with custom error handling in Fastify.

For example:
```js
Expand Down Expand Up @@ -217,23 +228,6 @@ fastify.listen({ port: 3000 }, function (err, address) {
})
```

If a plugin's error handler re-throws
an error, and the error is not an instance of
[Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
(as seen in the `/bad` route), it
won't propagate to the parent context error handler.
Instead, it will be caught by the default error handler.

To ensure consistent error handling,
it's recommended to throw instances of Error.
For instance, replacing `throw 'foo'`
with `throw new Error('foo')` in the
`/bad` route would ensure that errors
propagate through the custom error handling chain as intended.
This practice helps to avoid potential
pitfalls when working with custom
error handling in Fastify.

### Fastify Error Codes
<a id="fastify-error-codes"></a>

Expand Down

0 comments on commit cf6a87b

Please sign in to comment.