fastify / fastify-sensible

Defaults for Fastify that everyone can agree on

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Expose isHttpError function from http-errors

mikicho opened this issue · comments

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

Thanks for reporting! I'm not sure what's the problem is in just checking if the statusCode property is defined. Relying on instanceof in JS is not a great idea either.

Thanks! I was afraid of some unexpected behavior but I tend to agree there is a small chance for this to happen in this case.