Skip to content

Commit eca6312

Browse files
author
codershiba
authored
chore(docs): Add clarification about fastify.setErrorHandler() (fastify#5265)
1 parent f176719 commit eca6312

File tree

1 file changed

+66
-1
lines changed

1 file changed

+66
-1
lines changed

docs/Reference/Errors.md

+66-1
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,71 @@ Some things to consider in your custom error handler:
169169
internally monitors the error invocation to avoid infinite loops for errors
170170
thrown in the reply phases of the lifecycle. (those after the route handler)
171171

172+
**Important**: When utilizing Fastify's custom error handling through
173+
[`setErrorHandler`](./Server.md#seterrorhandler),
174+
it's crucial to be aware of how errors
175+
are propagated between custom and default error handlers.
176+
177+
For example:
178+
```js
179+
const Fastify = require('fastify')
180+
181+
// Instantiate the framework
182+
const fastify = Fastify({
183+
logger: true
184+
})
185+
186+
// Register parent error handler
187+
fastify.setErrorHandler((error, request, reply) => {
188+
reply.status(500).send({ ok: false })
189+
})
190+
191+
fastify.register((app, options, next) => {
192+
// Register child error handler
193+
fastify.setErrorHandler((error, request, reply) => {
194+
throw error
195+
})
196+
197+
fastify.get('/bad', async () => {
198+
// Throws a non-Error type, 'bar'
199+
throw 'foo'
200+
})
201+
202+
fastify.get('/good', async () => {
203+
// Throws an Error instance, 'bar'
204+
throw new Error('bar')
205+
})
206+
207+
next()
208+
})
209+
210+
// Run the server
211+
fastify.listen({ port: 3000 }, function (err, address) {
212+
if (err) {
213+
fastify.log.error(err)
214+
process.exit(1)
215+
}
216+
// Server is listening at ${address}
217+
})
218+
```
219+
220+
If a plugin's error handler re-throws
221+
an error, and the error is not an instance of
222+
[Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
223+
(as seen in the `/bad` route), it
224+
won't propagate to the parent context error handler.
225+
Instead, it will be caught by the default error handler.
226+
227+
To ensure consistent error handling,
228+
it's recommended to throw instances of Error.
229+
For instance, replacing `throw 'foo'`
230+
with `throw new Error('foo')` in the
231+
`/bad` route would ensure that errors
232+
propagate through the custom error handling chain as intended.
233+
This practice helps to avoid potential
234+
pitfalls when working with custom
235+
error handling in Fastify.
236+
172237
### Fastify Error Codes
173238
<a id="fastify-error-codes"></a>
174239

@@ -183,7 +248,7 @@ const errorCodes = require('fastify').errorCodes
183248

184249
For example:
185250
```js
186-
const Fastify = require('./fastify')
251+
const Fastify = require('fastify')
187252

188253
// Instantiate the framework
189254
const fastify = Fastify({

0 commit comments

Comments
 (0)