Fastify HTTP Errors Enhanced Plugin

7.0.1 · active · verified Wed Apr 22

This plugin for Fastify integrates `http-errors-enhanced` to provide comprehensive and customizable error handling for web applications. It allows developers to configure how 404 errors are handled, whether unhandled server errors expose stack traces in production, and how validation errors (both request and response) are structured. The current stable version is 7.0.1. Releases appear to follow major version bumps for Node.js compatibility changes and minor/patch releases for bug fixes and dependency updates, indicating an active and well-maintained project with a steady, predictable cadence. A key differentiator is its ability to convert validation errors into a structured, human-readable format and its extensibility for modifying error processing or customizing AJV instances for response validation. It provides a consistent error response format compatible with standard Fastify errors, capable of including custom properties and headers derived from the enhanced error objects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to register the `fastify-http-errors-enhanced` plugin, configure its options, and throw an enhanced `NotFoundError` within a route handler to see the custom error response format and headers in action. It also shows a basic working route.

import fastify from 'fastify'
import fastifyHttpErrorsEnhanced from 'fastify-http-errors-enhanced'
import { NotFoundError } from 'http-errors-enhanced'

const server = fastify()

// Due to fastify-http-errors-enhanced using an onRoute hook, you must
// either use `await register` or wrap route definitions in a plugin.
await server.register(fastifyHttpErrorsEnhanced, {
  // Example options
  use422ForValidationErrors: true,
  hideUnhandledErrors: process.env.NODE_ENV === 'production'
})

server.get('/invalid', {
  handler: async function (request, reply) {
    throw new NotFoundError('This resource was not found.', {
      header: { 'X-Request-ID': request.id },
      code: 'RESOURCE_NOT_FOUND'
    })
  }
})

server.get('/ping', async (request, reply) => {
  return { status: 'ok' }
})

server.listen({ port: 3000 }, (err) => {
  if (err) {
    server.log.error(err)
    process.exit(1)
  }
  console.log(`Server listening on http://localhost:3000`)
})

view raw JSON →