npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fastify-http-errors-enhanced

v5.0.4

Published

A error handling plugin for Fastify that uses enhanced HTTP errors.

Downloads

1,497

Readme

fastify-http-errors-enhanced

Version Dependencies Build Coverage

A error handling plugin for Fastify that uses enhanced HTTP errors.

http://sw.cowtech.it/fastify-http-errors-enhanced

Installation

Just run:

npm install fastify-http-errors-enhanced --save

Usage

Register as a plugin, optional providing any of the following options:

  • handle404Errors: If to set an handler via setNotFoundHandler.
  • hideUnhandledErrors: If to hide unhandled server errors or returning to the client including stack information. Default is to hide errors when NODE_ENV environment variable is production.
  • use422ForValidationErrors: If to return 422 (Unprocessable Entity) instead of 400 (Bad Request) in case of validation errors.
  • convertValidationErrors: Convert validation errors to a structured human readable object. Default is true.
  • convertResponsesValidationErrors: Convert response validation errors to a structured human readable object. Default is to enable when NODE_ENV environment variable is different from production.
  • allowUndeclaredResponses: When converting response validation errors, allow responses that have no schema defined instead of throwing an error.
  • responseValidatorCustomizer: A function that receives a Ajv instances before compiling all response schemas. This can be used to add custom keywords, formats and so on.
  • preHandler: A function invoked before the error handlers that can modify the original error thrown. The function must accept the error as first argument and return the error to process.

Once registered, the server will use the plugin handlers for all errors (basically, both setErrorHandler and setNotFoundHandler are called).

The handler response format will compatible with standard fastify error response, which is the following:

{
  statusCode: number
  error: string
  message: string
}

If the original error's code properties does not start with HTTP_ERROR_ (http-errors-enhanced standard error prefix), then the code is also included in output object. In addition, the response headers will contain all headers defined in error.headers and the response body will contain all additional enumerable properties of the error.

To clarify, take this server as a example:

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

const server = fastify()

/*
Since fastify-http-errors-enhanced uses an onRoute hook, you have to either:

* use `await register...`
* wrap you routes definitions in a plugin

See: https://www.fastify.io/docs/latest/Guides/Migration-Guide-V4/#synchronous-route-definitions
*/
await server.register(fastifyHttpErrorsEnhanced)

server.get('/invalid', {
  handler: async function (request, reply) {
    throw new NotFoundError('You are not supposed to reach this.', {
      header: { 'X-Req-Id': request.id, id: 123 },
      code: 'UNREACHABLE'
    })
  }
})

server.listen({ port: 3000 }, err => {
  if (err) {
    throw err
  }
})

When hitting /invalid it will return the following:

{
  "error": "Not Found",
  "code": "UNREACHABLE",
  "message": "You are not supposed to reach this.",
  "statusCode": 404,
  "id": 123
}

and the X-Req-Id will be set accordingly.

Unhandled error handling

Once installed the plugin will also manage unhandled server errors.

In particular, if error hiding is enabled, all unhandled errors will return the following response:

{
  "error": "Internal Server Error",
  "message": "An error occurred trying to process your request.",
  "statusCode": 500
}

and the error will be logged using error severity.

If not hidden, instead, the error will be returned in a standard response that also add the stack property (as a array of strings) and any additional error enumerable property.

To clarify, take this server as a example:

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

await server.register(fastifyHttpErrorsEnhanced, { hideUnhandledErrors: false })

server.get('/invalid', {
  handler(request, reply) {
    const error = new Error('This was not supposed to happen.')
    error.id = 123
    throw error
  }
})

server.listen({ port: 3000 }, err => {
  if (err) {
    throw err
  }
})

When hitting /invalid it will return the following:

{
  "error": "Internal Server Error",
  "message": "[Error] This was not supposed to happen.",
  "statusCode": 500,
  "id": 123,
  "stack": ["..."]
}

Validation and response validation errors

If enabled, response will have status of 400 or 500 (depending on whether the request or response validation failed) and the the body will have the failedValidations property.

Example of a client validation error:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "One or more validations failed trying to process your request.",
  "failedValidations": { "query": { "val": "must match pattern \"ab{2}c\"", "val2": "is not a valid property" } }
}

Example of a response validation error:

{
  "error": "Internal Server Error",
  "message": "The response returned from the endpoint violates its specification for the HTTP status 200.",
  "statusCode": 500,
  "failedValidations": {
    "response": {
      "a": "must be a string",
      "b": "must be present",
      "c": "is not a valid property"
    }
  }
}

ESM Only

This package only supports to be directly imported in a ESM context.

For informations on how to use it in a CommonJS context, please check this page.

Contributing to fastify-http-errors-enhanced

  • Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
  • Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
  • Fork the project.
  • Start a feature/bugfix branch.
  • Commit and push until you are happy with your contribution.
  • Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.

Copyright

Copyright (C) 2019 and above Shogun ([email protected]).

Licensed under the ISC license, which can be found at https://choosealicense.com/licenses/isc.