Skip to content

Commit

Permalink
🔧 fix: unwrap transform errors (#882)
Browse files Browse the repository at this point in the history
  • Loading branch information
crishoj committed Oct 19, 2024
1 parent 22b79ce commit babd91a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
5 changes: 3 additions & 2 deletions src/compose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2343,9 +2343,10 @@ export const composeErrorHandler = (
}

fnLiteral += `if(error.constructor.name === "ValidationError" || error.constructor.name === "TransformDecodeError") {
set.status = error.status ?? 422
const reportedError = error.error ?? error
set.status = reportedError.status ?? 422
return new Response(
error.message,
reportedError.message,
{
headers: Object.assign(
{ 'content-type': 'application/json'},
Expand Down
11 changes: 7 additions & 4 deletions src/dynamic-handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { redirect, signCookie, StatusMap } from './utils'
import { parseCookie } from './cookies'

import type { Handler, LifeCycleStore, SchemaValidator } from './types'
import { TransformDecodeError } from '@sinclair/typebox/value'

// JIT Handler
export type DynamicHandler = {
Expand Down Expand Up @@ -420,11 +421,13 @@ export const createDynamicHandler =

return (context.response = mapResponse(response, context.set))
} catch (error) {
if ((error as ElysiaErrors).status)
set.status = (error as ElysiaErrors).status

const reportedError = (error instanceof TransformDecodeError && error.error)
? error.error
: error
if ((reportedError as ElysiaErrors).status)
set.status = (reportedError as ElysiaErrors).status
// @ts-expect-error private
return app.handleError(context, error)
return app.handleError(context, reportedError)
} finally {
for (const afterResponse of app.event.afterResponse)
await afterResponse.fn(context as any)
Expand Down
21 changes: 21 additions & 0 deletions test/core/handle-error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,25 @@ describe('Handle Error', () => {
'APIError'
)
})

it('handle error in Transform', async () => {
const route = new Elysia().get('/', ({query: {aid}}) => aid, {
query: t.Object({
aid: t.Transform(t.String())
.Decode((value) => {
throw new NotFoundError('foo')
})
.Encode((value) => `1`)
})
})

let response = await (new Elysia({ aot: false })).use(route).handle(req('/?aid=a'))
expect(response.status).toEqual(404)
expect(await response.text()).toEqual('foo')

response = await (new Elysia({aot: true})).use(route).handle(req('/?aid=a'))
expect(response.status).toEqual(404)
expect(await response.text()).toEqual('foo')
})

})

0 comments on commit babd91a

Please # to comment.