Skip to content

Incorrect error type in setErrorHandler #6116

@paulius-valiunas

Description

@paulius-valiunas

Prerequisites

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

Fastify version

5.2.2

Plugin version

No response

Node.js version

22.14.0

Operating system

Linux

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

Manjaro (rolling release)

Description

Route handlers are allowed to throw errors that can then be handled by a global or plugin-scoped error handler (.setErrorHandler()). The problem is that the setErrorHandler function always assumes the error originates from Fastify internals and automatically infers fastify.FastifyError as the error type. If the error was thrown from a route handler, this assumption is most likely incorrect and can result in a TypeError. Fastify should either infer the error type to unknown (which is the behavior or catch blocks), or wrap any error thrown from a route handler in its own expected format.

The minimal reproducible example demonstrates how Typescript fails to prevent a TypeError which is then shown to the client.

Here is the resulting HTTP response body:

{
	"statusCode": 500,
	"error": "Internal Server Error",
	"message": "Cannot read properties of undefined (reading 'toUpperCase')"
}

Link to code that reproduces the bug

https://github.com/paulius-valiunas/fastify-error-repro

Expected Behavior

src/index.ts:4:21 - error TS2339: Property 'code' does not exist on type 'unknown'.

4   console.log(error.code); // prints undefined
                      ~~~~


Found 1 error in src/index.ts:4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bugtypescriptTypeScript related

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions