Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/compose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2058,8 +2058,8 @@ export const composeHandler = ({
'c.code="VALIDATION"\n' +
'c.set.status=422' +
'}else{' +
`c.code=error.code??error[ERROR_CODE]??"UNKNOWN"}`
else fnLiteral += `c.code=error.code??error[ERROR_CODE]??"UNKNOWN"\n`
`c.code=error[ERROR_CODE]??error.code??"UNKNOWN"}`
else fnLiteral += `c.code=error[ERROR_CODE]??error.code??"UNKNOWN"\n`

fnLiteral += `let er\n`
// Mapped error Response
Expand Down Expand Up @@ -2657,7 +2657,7 @@ export const composeErrorHandler = (app: AnyElysia) => {
fnLiteral +=
`const set=context.set\n` +
`let _r\n` +
`if(!context.code)context.code=error.code??error[ERROR_CODE]\n` +
`if(!context.code)context.code=error[ERROR_CODE]??error.code\n` +
`if(!(context.error instanceof Error))context.error=error\n` +
`if(error instanceof ElysiaCustomStatusResponse){` +
`set.status=error.status=error.code\n` +
Expand Down
10 changes: 9 additions & 1 deletion src/dynamic-handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Context } from './context'
import { parseCookie } from './cookies'
import {
ElysiaCustomStatusResponse,
ERROR_CODE,
type ElysiaErrors,
NotFoundError,
status,
Expand Down Expand Up @@ -880,7 +881,14 @@ export const createDynamicErrorHandler = (app: AnyElysia) => {
},
error: ElysiaErrors
) => {
const errorContext = Object.assign(context, { error, code: error.code })
const registeredCode = (error as Error & { [ERROR_CODE]?: string })[
ERROR_CODE
]

const errorContext = Object.assign(context, {
error,
code: registeredCode ?? error.code
})
errorContext.set = context.set

if (
Expand Down
28 changes: 28 additions & 0 deletions test/lifecycle/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,34 @@ describe('error', () => {
expect(response.status).toBe(500)
})

it.each([true, false])(
'uses registered error key over instance code with aot: %p',
async (aot) => {
class InvalidUrlError extends Error {
code = 'invalid_url' as const

constructor() {
super('internal message')
}
}

const app = new Elysia({ aot })
.error({ INVALID_URL: InvalidUrlError })
.onError(({ code }) => {
if (code === 'INVALID_URL')
return new Response('handled', { status: 422 })
})
.get('/', () => {
throw new InvalidUrlError()
})

const response = await app.handle(req('/'))

expect(response.status).toBe(422)
expect(await response.text()).toBe('handled')
}
)

it.each([true, false])(
'return correct number status on error function with aot: %p',
async (aot) => {
Expand Down