Skip to content

onError returning status() corrupts the shared NotFoundError singleton - every 404 after the first becomes a 500 #1969

Description

@guiwatanabe

What version of Elysia is running?

elysia@1.4.29

What platform is your computer?

Darwin 25.5.0 arm64 arm

What environment are you using

1.3.14

Are you using dynamic mode?

No

What steps can reproduce the bug?

When a global onError handler returns a status(...) response, Elysia mutates the thrown error instead of the returned response. For unmatched routes this mutates the single NotFoundError instance that composeGeneralHandler creates once and reuses for every request, so the corruption persists for the lifetime of the server:

  • 1st unmatched request: error.status === 404, error.message === "NOT_FOUND"
  • every subsequent unmatched request: error.status === "NOT_FOUND" (the string code), error.message === undefined

Custom error-translation logic reading error.status then misbehaves from the second 404 onward (in our production app, all unmatched routes returned 500 after the first 404).

import { Elysia, NotFoundError } from 'elysia'

new Elysia()
    .onError(({ error, status }) => {
        if (error instanceof NotFoundError)
            console.log('thrown with status:', error.status, '| message:', error.message)
        return status(404, 'custom not found body')
    })
    .listen(3000)

await fetch('http://localhost:3000/missing')
await fetch('http://localhost:3000/missing')

Output:

thrown with status: 404 | message: NOT_FOUND
thrown with status: NOT_FOUND | message: undefined

What is the expected behavior?

Read the status/message from the returned response, not the thrown error - e.g. error.status = _r.code; error.message = _r.response - or avoid mutating the shared NotFoundError instance at all (construct it per request, or freeze it).

What do you see instead?

No response

Additional information

In src/compose.ts:2699 (composeErrorHandler), the block handling an onError handler's return value guards on _r but mutates error:

					`if(_r instanceof ElysiaCustomStatusResponse){` +
					`error.status=error.code\n` +
					`error.message=error.response` +
					`}`

Somewhat related issue: #1363

Have you try removing the node_modules and bun.lock and try again yet?

Yes

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions