In Node.js, uncaught errors are likely to cause memory leaks, file descriptor leaks, and other major production issues. Domains were a failed attempt to fix this.
Given that it is not possible to process all uncaught errors sensibly, the best way to deal with them is to crash.
If you are using promises, you should attach a .catch()
handler synchronously.
Fastify follows an all-or-nothing approach and aims to be lean and optimal as much as possible. The developer is responsible for making sure that the errors are handled properly.
Most errors are a result of unexpected input data, so we recommend validating your input data against a JSON schema.
Fastify tries to catch as many uncaught errors as it can without hindering performance. This includes:
- synchronous routes, e.g.
app.get('/', () => { throw new Error('kaboom') })
async
routes, e.g.app.get('/', async () => { throw new Error('kaboom') })
The error in both cases will be caught safely and routed to Fastify's default
error handler for a generic 500 Internal Server Error
response.
To customize this behavior you should use
setErrorHandler
.
From the Hooks documentation:
If you get an error during the execution of your hook, just pass it to
done()
and Fastify will automatically close the request and send the appropriate error code to the user.
When a custom error handler has been defined through
setErrorHandler
, the custom error handler will
receive the error passed to the done()
callback (or through other supported
automatic error handling mechanisms). If setErrorHandler
has been used
multiple times to define multiple handlers, the error will be routed to the most
precedent handler defined within the error encapsulation
context. Error handlers are fully encapsulated, so a
setErrorHandler
call within a plugin will limit the error handler to that
plugin's context.
The root error handler is Fastify's generic error handler. This error handler
will use the headers and status code in the Error
object, if they exist. The
headers and status code will not be automatically set if a custom error handler
is provided.
Some things to consider in your custom error handler:
-
you can
reply.send(data)
, which will behave as it would in regular route handlers- objects are serialized, triggering the
preSerialization
lifecycle hook if you have one defined - strings, buffers, and streams are sent to the client, with appropriate headers (no serialization)
- objects are serialized, triggering the
-
You can throw a new error in your custom error handler - errors (new error or the received error parameter re-thrown) - will call the parent
errorHandler
.onError
hook will be triggered once only for the first error being thrown.- an error will not be triggered twice from a lifecycle hook - Fastify internally monitors the error invocation to avoid infinite loops for errors thrown in the reply phases of the lifecycle. (those after the route handler)
You can access errorCodes
for mapping:
// ESM
import { errorCodes } from 'fastify'
// CommonJs
const errorCodes = require('fastify').errorCodes
For example:
const Fastify = require('./fastify')
// Instantiate the framework
const fastify = Fastify({
logger: true
})
// Declare a route
fastify.get('/', function (request, reply) {
reply.code('bad status code').send({ hello: 'world' })
})
fastify.setErrorHandler(function (error, request, reply) {
if (error instanceof Fastify.errorCodes.FST_ERR_BAD_STATUS_CODE) {
// Log error
this.log.error(error)
// Send error response
reply.status(500).send({ ok: false })
} else {
// fastify will use parent error handler to handle this
reply.send(error)
}
})
// Run the server!
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
// Server is now listening on ${address}
})
404 Not Found.
Fastify options must be an object.
QueryStringParser option should be a function.
SchemaController.bucket option should be a function.
SchemaErrorFormatter option should be a non async function.
ajv.customOptions option should be an object.
ajv.plugins option should be an array.
Version constraint should be a string.
The parser for this content type was already registered.
The Content-Type
should be a string.
The content type cannot be an empty string.
An invalid handler was passed for the content type.
The provided parse type is not supported. Accepted values are string
or
buffer
.
The request body is larger than the provided limit.
This setting can be defined in the Fastify server instance:
bodyLimit
The received media type is not supported (i.e. there is no suitable
Content-Type
parser for it).
Request body size did not match Content-Length
.
Body cannot be empty when content-type is set to application/json
.
Fastify is already started.
Fastify instance is already listening.
A decorator with the same name is already registered.
The dependencies of decorator must be of type Array
.
The decorator cannot be registered due to a missing dependency.
The decorator cannot be added after start.
The hook name must be a string.
The hook callback must be a function.
The hook is not supported.
You must register a plugin for handling middlewares,
visit Middleware
for more info.
A callback for a hook timed out
The logger accepts either a 'stream'
or a 'file'
as the destination.
Reply payload can be either a string
or a Buffer
.
A response was already sent.
The only possible value for reply.sent
is true
.
You cannot use send
inside the onError
hook.
Undefined error has occurred.
Called reply
with an invalid status code.
Called reply.trailer
with an invalid header name.
Called reply.trailer
with an invalid type. Expected a function.
Missing serialization function.
Invalid validation invocation. Missing validation function for HTTP part nor schema provided.
The schema provided does not have $id
property.
A schema with the same $id
already exists.
Schema with the same $id
already present!
The JSON schema provided for validation to a route is not valid.
The JSON schema provided for serialization of a route response is not valid.
Response schemas should be nested under a valid status code (2XX).
HTTP2 is available only from node >= 8.8.1.
Invalid initialization options.
Cannot set forceCloseConnections to idle
as your HTTP server
does not support closeIdleConnections
method.
The HTTP method already has a registered controller for that URL
The router received an invalid url.
The router received an error when using asynchronous constraints.
The defaultRoute
type should be a function.
URL must be a string.
Options for the route must be an object.
Duplicate handler for the route is not allowed.
Handler for the route must be a function.
Missing handler function for the route.
Method is not supported for the route.
Body validation schema route is not supported.
BodyLimit option must be an integer.
Rewrite url needs to be of type "string".
Fastify has already been closed and cannot be reopened.
Fastify is already listening.
Installed Fastify plugin mismatched expected version.
Callback for a hook is not a function (mapped directly from avvio
)
Plugin must be a function or a promise.
Root plugin has already booted (mapped directly from avvio
)
Impossible to load plugin because the parent (mapped directly from avvio
)
Plugin did not start in time. Default timeout (in millis): 10000
The decorator is not present in the instance.