GithubHelp home page GithubHelp logo

fastify / fastify-sensible Goto Github PK

View Code? Open in Web Editor NEW
453.0 18.0 34.0 180 KB

Defaults for Fastify that everyone can agree on

License: MIT License

JavaScript 82.17% TypeScript 17.83%
fastify defaults utility http fastify-plugin

fastify-sensible's Introduction

@fastify/sensible

CI NPM version js-standard-style

Defaults for Fastify that everyone can agree onβ„’.
This plugin adds some useful utilities to your Fastify instance, see the API section to learn more.

Why are these APIs here and not included with Fastify?
Because Fastify aims to be as small and focused as possible, every utility that is not essential should be shipped as a standalone plugin.

Install

npm i @fastify/sensible

Compatibility

Plugin version Fastify version
^5.0.0 ^4.0.0
^4.0.0 ^3.0.0
^2.0.0 ^2.0.0
^1.0.0 ^1.0.0

Please note that if a Fastify version is out of support, then so are the corresponding version(s) of this plugin in the table above. See Fastify's LTS policy for more details.

Usage

const fastify = require('fastify')()
fastify.register(require('@fastify/sensible'))

fastify.get('/', (req, reply) => {
  reply.notFound()
})

fastify.get('/async', async (req, reply) => {
  throw fastify.httpErrors.notFound()
})

fastify.get('/async-return', async (req, reply) => {
  return reply.notFound()
})

fastify.listen({ port: 3000 })

Shared JSON Schema for HTTP errors

If you set the sharedSchemaId option, a shared JSON Schema is added and can be used in your routes.

const fastify = require('fastify')()
fastify.register(require('@fastify/sensible'), {
  sharedSchemaId: 'HttpError'
})

fastify.get('/async', {
  schema: {
    response: {
      404: { $ref: 'HttpError' }
    }
  },
  handler: async (req, reply) => {
    return reply.notFound()
  }
})

fastify.listen({ port: 3000 })

API

fastify.httpErrors

Object that exposes createError and all of the 4xx and 5xx error constructors.

Use of 4xx and 5xx error constructors follows the same structure as new createError[code || name]([msg])) in http-errors:

 // the custom message is optional
const notFoundErr = fastify.httpErrors.notFound('custom message')

4xx

  • fastify.httpErrors.badRequest()
  • fastify.httpErrors.unauthorized()
  • fastify.httpErrors.paymentRequired()
  • fastify.httpErrors.forbidden()
  • fastify.httpErrors.notFound()
  • fastify.httpErrors.methodNotAllowed()
  • fastify.httpErrors.notAcceptable()
  • fastify.httpErrors.proxyAuthenticationRequired()
  • fastify.httpErrors.requestTimeout()
  • fastify.httpErrors.conflict()
  • fastify.httpErrors.gone()
  • fastify.httpErrors.lengthRequired()
  • fastify.httpErrors.preconditionFailed()
  • fastify.httpErrors.payloadTooLarge()
  • fastify.httpErrors.uriTooLong()
  • fastify.httpErrors.unsupportedMediaType()
  • fastify.httpErrors.rangeNotSatisfiable()
  • fastify.httpErrors.expectationFailed()
  • fastify.httpErrors.imateapot()
  • fastify.httpErrors.misdirectedRequest()
  • fastify.httpErrors.unprocessableEntity()
  • fastify.httpErrors.locked()
  • fastify.httpErrors.failedDependency()
  • fastify.httpErrors.tooEarly()
  • fastify.httpErrors.upgradeRequired()
  • fastify.httpErrors.preconditionRequired()
  • fastify.httpErrors.tooManyRequests()
  • fastify.httpErrors.requestHeaderFieldsTooLarge()
  • fastify.httpErrors.unavailableForLegalReasons()

5xx

  • fastify.httpErrors.internalServerError()
  • fastify.httpErrors.notImplemented()
  • fastify.httpErrors.badGateway()
  • fastify.httpErrors.serviceUnavailable()
  • fastify.httpErrors.gatewayTimeout()
  • fastify.httpErrors.httpVersionNotSupported()
  • fastify.httpErrors.variantAlsoNegotiates()
  • fastify.httpErrors.insufficientStorage()
  • fastify.httpErrors.loopDetected()
  • fastify.httpErrors.bandwidthLimitExceeded()
  • fastify.httpErrors.notExtended()
  • fastify.httpErrors.networkAuthenticationRequired()

createError

Use of createError follows the same structure as createError([status], [message], [properties]) in http-errors:

var err = fastify.httpErrors.createError(404, 'This video does not exist!')

reply.[httpError]

The reply interface is decorated with all of the functions declared above, using it is easy:

fastify.get('/', (req, reply) => {
  reply.notFound()
})

reply.vary

The reply interface is decorated with jshttp/vary, the API is the same, but you do not need to pass the res object.

fastify.get('/', (req, reply) => {
  reply.vary('Accept')
  reply.send('ok')
})

reply.cacheControl

The reply interface is decorated an helper to configure cache control response headers.

// configure a single type
fastify.get('/', (req, reply) => {
  reply.cacheControl('public')
  reply.send('ok')
})

// configure multiple types
fastify.get('/', (req, reply) => {
  reply.cacheControl('public')
  reply.cacheControl('immutable')
  reply.send('ok')
})

// configure a type time
fastify.get('/', (req, reply) => {
  reply.cacheControl('max-age', 42)
  reply.send('ok')
})

// the time can be defined as string
fastify.get('/', (req, reply) => {
  // all the formats of github.com/vercel/ms are supported
  reply.cacheControl('max-age', '1d') // will set to 'max-age=86400'
  reply.send('ok')
})

reply.preventCache

The reply interface is decorated with a helper to set the cache control header to a no caching configuration.

fastify.get('/', (req, reply) => {
  // will set cache-control to 'no-store, max-age=0, private'
  // and for HTTP/1.0 compatibility
  // will set pragma to 'no-cache' and expires to 0
  reply.preventCache()
  reply.send('ok')
})

reply.revalidate

The reply interface is decorated with a helper to set the cache control header to a no caching configuration.

fastify.get('/', (req, reply) => {
  reply.revalidate() // will set to 'max-age=0, must-revalidate'
  reply.send('ok')
})

reply.staticCache

The reply interface is decorated with a helper to set the cache control header to a public and immutable configuration.

fastify.get('/', (req, reply) => {
  // the time can be defined as a string
  reply.staticCache(42) // will set to 'public, max-age=42, immutable'
  reply.send('ok')
})

reply.stale

The reply interface is decorated with a helper to set the cache control header for stale content.

fastify.get('/', (req, reply) => {
  // the time can be defined as a string
  reply.stale('while-revalidate', 42)
  reply.stale('if-error', 1)
  reply.send('ok')
})

reply.maxAge

The reply interface is decorated with a helper to set max age of the response. It can be used in conjunction with reply.stale, see here.

fastify.get('/', (req, reply) => {
  // the time can be defined as a string
  reply.maxAge(86400)
  reply.stale('while-revalidate', 42)
  reply.send('ok')
})

request.forwarded

The request interface is decorated with jshttp/forwarded, the API is the same, but you do not need to pass the request object:

fastify.get('/', (req, reply) => {
  reply.send(req.forwarded())
})

request.is

The request interface is decorated with jshttp/type-is, the API is the same, but you do not need to pass the request object:

fastify.get('/', (req, reply) => {
  reply.send(req.is(['html', 'json']))
})

assert

Verify if a given condition is true, if not it throws the specified http error.
Useful if you work with async routes:

// the custom message is optional
fastify.assert(
  req.headers.authorization, 400, 'Missing authorization header'
)

The assert API also exposes the following methods:

  • fastify.assert.ok()
  • fastify.assert.equal()
  • fastify.assert.notEqual()
  • fastify.assert.strictEqual()
  • fastify.assert.notStrictEqual()
  • fastify.assert.deepEqual()
  • fastify.assert.notDeepEqual()

to

Async await wrapper for easy error handling without try-catch, inspired by await-to-js:

const [err, user] = await fastify.to(
  db.findOne({ user: 'tyrion' })
)

Contributing

Do you feel there is some utility that everyone can agree on which is not present?
Open an issue and let's discuss it! Even better a pull request!

Acknowledgements

The project name is inspired by vim-sensible, an awesome package that if you use vim you should use too.

License

MIT Copyright Β© Tomas Della Vedova & Fastify collaborators

fastify-sensible's People

Contributors

0xvbetsun avatar allevo avatar arthurfiorette avatar cemremengu avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar despian avatar dustinspecker avatar eomm avatar fdawgs avatar github-actions[bot] avatar gkampitakis avatar gurgunday avatar hsynlms avatar jean-michelet avatar jgiola avatar jsumners avatar khendrikse avatar lqqyt2423 avatar mcollina avatar mosheikh avatar r-a-f-a avatar rafaelgss avatar robinvdvleuten avatar salmanm avatar sergejostir avatar sinedied avatar uzlopak avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-sensible's Issues

`fastify` types can't be extended properly in monorepo with yarn + pnpm nodeLinker

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

>=4

Plugin version

>=5

Node.js version

20

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

14.1

Description

Since solution suggested in #154 was not accepted, I'm opening an issue here to find alternative solution

In environments with pnpm and yarn with linker: pnpm, and inside a monorepo, typescript fails to resolve the types of fastify and can't extend the interfaces of fastify properly.

During type-checking, tsc fails with the following error:
Typescript should fail with the following error:

index.ts:8:9 - error TS2339: Property 'notFound' does not exist on type 'FastifyReply<Server<typeof IncomingMessage, typeof ServerResponse>, IncomingMessage, ServerResponse<IncomingMessage>, ... 4 more ..., unknown>'.
8   reply.notFound();
          ~~~~~~~~

Found 1 error in index.ts:8

As a side-note: in local environment this can be fixed by adding the following .yarnrc.yml:

packageExtensions:
  "@fastify/sensible@*":
    peerDependencies:
      fastify: "*"

Steps to Reproduce

Reproduction repository: https://github.com/jbroma/ffy-sensible-repro

Steps to reproduce:

  1. Clone the repository
  2. Install dependencies with yarn
  3. Run yarn typecheck

Expected Behavior

Fastify types are properly extended

`to` errors should have customizable type arguments or inference

πŸ› Bug Report

The type used for the error is the plain Error type so if you have a different error like something from got where it has properties like code it throws errors. You can cast the error as your particular type but it'd be nice to be able to provide the type argument like you can for the data you expect.

To Reproduce

Steps to reproduce the behavior:

const [someError, data] = await app.to(someFuncWithCustomError(arg))

if (someError.customProperty) { // oh no TS no likey!
}

Expected behavior

Either a way to provide explicit typing or proper inference

// inference
const [someError, data] = await app.to(someFuncWithCustomError(arg))

if (someError.customProperty) { 
}

// explicit
const [someError, data] = await app.to<MyData, MyError>(someFuncWithCustomError(arg)) // suggestion swap type args to match func args with error type first?

if (someError.customProperty) { 
}

Your Environment

  • node version: 14
  • fastify version: >=3.15.0
  • os: Linux/Docker run images on Mac dev box

Expose errors at package level

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

I am writing some REST API and I really enjoyed this package.
However, I am feeling the need to offload the business logic from the handler and handle it in some objects with service pattern. At this layer I do not want to access fastify app.
My proposal is to expose http errors at package level so we can use them anywhere we want without having a fastify instance.

Motivation

We need to be able to use this errors anywhere we want without having access to a fastify instance.

Example

For example:

import { httpErrors } from 'fastify-sensible'

Make it possible to add 'properties' to httpErrors

πŸš€ Feature Proposal

When using server.httpErrors it would be nice to be able to also pass properties like you can do in the createError([status], [message], [properties]) options of http-errors. If this is not possible, maybe another option would be to have it expose createError() itself in case one might want to do:

server.httpErrors.createError(([status], [message], [properties])

Motivation

When using this library, a bit reason could be that one wants to use the httpErrors functionality. But right now it is only possible to parse along a message, while for some errors additional data might be required.

Example

Please provide an example for how this feature would be used.

server.httpErrors.badRequest(([status], [message], [properties])

or

server.httpErrors.createError(([status], [message], [properties])

ChainAlert: npm package release (3.2.0) has no matching tag in this repo

Dear fastify-sensible maintainers,
Thank you for your contribution to the open-source community.

This issue was automatically created to inform you a new version (3.2.0) of fastify-sensible was published without a matching tag in this repo.

As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

If you find this behavior legitimate, kindly close and ignore this issue. Read more

badge

`createError` function does not return custom properties

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.0.0

Plugin version

3.1.0

Node.js version

v14.17.6

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

I'm trying to return a custom property from an Http Error that I can use to Internationalize the error in the frontend. So just like a shorthand for the message.

throw fastify.httpErrors.createError(
  400,
  "The provided Email is already taken",
  { displayError: "emailTaken" }
);

But if the error gets triggered it still doesn't return the custom property displayError.
Below is the returned body:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Test"
}

Steps to Reproduce

The below route will not return the custom property in the error response.

fastify.post("/", async function (req, reply) {
  throw fastify.httpErrors.createError(
    400,
    "The provided Email is already taken",
    { displayError: "emailTaken" }
  );
});

Expected Behavior

I expect an Error response that is defined through the createError function with custom properties to also return them.

Maybe pagination?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

I'm trying to move from Express to Fastify.
I have been doing pagination in other projects simply as a middleware on allroutes (app level) to grab the requested page, then grab and use number of page (as an offset always in a query)

Just an example:

https://github.com/bacloud22/Classified-ads-48/blob/cee17333c9bebd18eb83564dd5d5080bbe572fcb/sexpress.js#L116

Used here

https://github.com/bacloud22/Classified-ads-48/blob/cee17333c9bebd18eb83564dd5d5080bbe572fcb/lib/routes/listings.js#L39

As you can see the logic here is very simple and maybe no customisation is needed
Ps: I can't work on this as I need to learn more about the philosophy here πŸ˜„

Thanks

Motivation

No response

Example

No response

[feature] add option to share schema

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

As all errors follows the same format, it would be useful to have an option similar to what exists in @fastify/multipart to provide a shared schema for errors, for those of us who use schemas for validation/swagger.

For example, using the option:

{
  sharedSchemaId: '#httpErrors',
}

Would allow to reference this in all route schemas.

Motivation

If you use schema for swagger, you'll have to write this schema in all your fastify apps.
This could be built-in in this plugin as it provides the error facilities. It would also make code most robust, in case you decide later to change the error response format, it would not break apps.

Example

No response

Expose isHttpError function from http-errors

Maybe I'm missing something silly, but I'm struggling with handling HTTP errors thrown by @fastify/sensible in a custom error handler.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

Expose isHttpError function from http-errors:

  fastify.setErrorHandler((error, request, reply) => {
    if (sensible.isHttpError(error)) {
      reply.code(error.statusCode).send(error)
    }
  })

Motivation

Handle http-errors easily instead of having a specific if for each HTTP error type in the error handler.

And I couldn't find a proper solution, my best try isn't Typescript friendly:

// The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.
if (error instanceof fastify.httpErrors.HttpError) {
}

Example

No response

How to override custom error handler

I like the request methods this plugin adds, but how would like to handle the errors myself. How do I override the custom error handler? I've tried to add it after and before registering this plugin, but it never gets called;

fastify.setErrorHandler(function (error, request, reply) {
  // Never called here...
})

fastify.register(require('fastify-sensible'))

fastify.setErrorHandler(function (error, request, reply) {
  // Never called here...
})

www-authenticate at UnauthorizedError

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

If the server responds with a 401 status code, RFC 7235 requires that the www-authenticate header be included. So it should be possible for the developers to set the values for the authentication type and the realm once, and all 401 errors should then contain the www-authenticate header with the appropriate values.

Motivation

This feature would make it much easier for developers to develop RFC compliantly. It would be optional to set these values, so using the plugin would not change if you don't want to use this feature.

Example

const fastify = require('fastify')()
const sensible = require('fastify-sensible')

fastify.register(sensible, {
  authenticationType: 'Basic',
  realm: 'MyApp'
})

// response would contain header www-authenticate with value 'Basic realm=MyApp'
fastify.get('/', async (req, res) => {
  throw this.httpErrors.unauthorized()
})

Change reply in onSend hook using Fastify sensible

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

I would love to use fastify-sensible. But in my case I check if the payload is empty and I want to set the "Not found" generic error using the reply.notFound() function.

However, it seems that it automatically also triggers a send again or something..?

Anyway, the function call will cause errors in onSend too bad 😒 (I do see the "not found" JSON message btw when calling the API, you only get those internal errors):

[14:29:07 UTC] ERROR: Promise errored, but reply.sent = true was set
    reqId: "req-1"
    err: {
      "type": "Error",
      "message": "Cannot write headers after they are sent to the client",
      "stack":
          Error [ERR_HTTP_HEADERS_SENT]: Cannot write headers after they are sent to the client
              at ServerResponse.writeHead (node:_http_server:345:11)
              at /media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/error-handler.js:42:19
              at fallbackErrorHandler (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/error-handler.js:127:3)
              at handleError (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/error-handler.js:34:5)
              at onErrorHook (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/reply.js:839:5)
              at wrapOnSendEnd (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/reply.js:563:5)
              at next (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/hooks.js:297:7)
              at onSendHookRunner (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/hooks.js:317:3)
              at onSendHook (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/reply.js:549:5)
              at Reply.send (/media/melroy/Data/Projects/erp-backend/node_modules/fastify/lib/reply.js:162:5)
      "code": "ERR_HTTP_HEADERS_SENT"
    }

Motivation

Currently I was creating my own errors like so, but I would like to leverage Fastify sensible in the onSend instead of reinventing the wheel here:

      reply.code(404).header('content-type', 'application/json; charset=utf-8')
      // Not found message
      const stringify = fastJson({
        type: 'object',
        properties: {
          message: {
            type: 'string'
          }
        }
      })
      const message = { message: 'Not found' }
      return done(null, stringify(message))

Example

Code that cause the error:

fastify.addHook('onSend', (req, reply, payload, done) => {
    if (!payload) {
      reply.notFound()
      return done()
    }
    
    ..... 
    .....
    done()
}

ES-module support?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

Could we please have ES-module support instead of Common.js, now that its supported by Node.js.
<3

Motivation

Some applications are written as ES-modules, and will have problem including this plugin if it only support common.js

Error starting up, error: ReferenceError: require is not defined in ES module scope, you can use import instead This file is being treated as an ES module because it has a '.js' file extension and '/home/trycoon/git/vision-remix/vision-backend/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension. at file:///home/trycoon/git/vision-remix/vision-backend/plugins/sensible.js:1:12 at ModuleJob.run (node:internal/modules/esm/module_job:218:25) at async ModuleLoader.import (node:internal/modules/esm/loader:329:24) at async importModuleDynamicallyWrapper (node:internal/vm/module:431:15) at async loadPlugin (/home/trycoon/git/vision-remix/vision-backend/node_modules/@fastify/autoload/index.js:271:15) at async Promise.all (index 0) at async autoload (/home/trycoon/git/vision-remix/vision-backend/node_modules/@fastify/autoload/index.js:43:3)

Example

No response

Add request.is() helper

I've added a helper in my projects to check what kind of type the request is in a similar way Express does it with jshttp/type-is;

const typeis = require('type-is')

fastify.decorateRequest('is', function (types) {
  return typeis(this.raw, Array.isArray(types) ? types : [types])
})

As this plugin already contains some other helpers from jshttp packages, maybe this would be a nice addition as well?

fastify.error()

πŸš€ Feature Proposal

It is harder to remember and type https status codes names, compared to numbers:

throw fastify.httpErrors.unauthorized('Incorrect password')

On the other hand the assert api is easy to read and write:

fastify.assert(false, 401, 'Incorrect password')

The proposal is to expose an error api to generate errors by status code.

fastify.error(401, 'Incorrect password')

or

throw fastify.error(401, 'Incorrect password')

Motivation

Make the error interface easier to use and more similar to fastify.assert()

Example

fastify.error(401, 'Incorrect password')

customErrorHandler should not obscure original error

πŸš€ Feature Proposal

When using the onError hook to log errors to monitoring services, it would be great to have access to the original error.

However this is not currently possible with fastify-sensible customErrorHandler, because it creates a new Error with a new stacktrace for unhandled 500 errors.

Motivation

Being able to log the original error without having to disable fastify-sensible customErrorHandler

Example

fastify.addHook('onError', async (request, reply, error) => {
    Sentry.captureException(error)
}

Fastify reply functions wrongly typed

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hi folks,

Looking at typings for fastify reply decorations added by this library in httpError.d.ts

// Line 103
export type HttpErrorReplys = {
  getHttpError: (code: HttpErrorCodes, message?: string) => void;
} & Record<HttpErrorNames, (msg?: string) => void>;

it looks like that those functions (rep.internalServerError('') for example) should return void.

However, looking at the implementation in index.js

// Line 47
fastify.decorateReply(httpError, function (message) {
  this.send(httpErrors[httpError](message))
  return this
})

it looks like that the reply object is returned after calling send function.

Could it be possible to align the typings so I can do the following in my code without a 'await' has no effect on the type of this expression.ts(80007) message and ESLint being mad?

fastify.get('/', { 
  async handler(req, rep) {
    return await rep.internalServerError('Oops')
  }
}

image

Thanks

Not found (404) custom message

Hi,
I try to set a custom message for a 404 notFound() function, but it is ignored. I always get "Not Found" as message.

Can't customize the message on errors with 500 status code

πŸ› Bug Report

When throwing or returning errors, the custom error message is overwritten when the status code is 500. It works with other status codes like 400 or 501.

To Reproduce

Steps to reproduce the behavior:

module.exports = async function (fastify, options) {
	fastify.register(require('fastify-sensible'))

	fastify.get('/fails/1', async function (req, reply) {
		return new Error('Not working') // responds  with default error message
	})
	fastify.get('/fails/2', async function (req, reply) {
		throw new Error('Not working') // responds  with default error message
	})
	fastify.get('/fails/3', async function (req, reply) {
		reply.code(500)
		throw new Error('Not working') // responds  with default error message
	})

	fastify.get('/works/1', async function (req, reply) {
		reply.code(500)
		return 'This works'
	})
	fastify.get('/works/2', async function (req, reply) {
		reply.code(501)
		throw new Error('This works')
	})
	fastify.get('/works/3', async function (req, reply) {
		reply.code(400)
		throw new Error('This works')
	})
}

Expected behavior

The custom error message should always be respected.

Your Environment

  • node version: 12.14.0
  • fastify-cli version: 1.5.0
  • os: Mac

Moved from fastify/fastify#2246

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.