Skip to content
Draft
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
42 changes: 42 additions & 0 deletions src/compose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,48 @@ describe('compose with Context - 500 error', () => {
expect(stack).toEqual([0, 1, 2])
})
})

describe('compose with Context - Handling throwing a non-Error object', () => {
const req = new Request('http://localhost/')
const c: Context = new Context(req)

it('String', async () => {
const nonErrorString = 'Something went wrong'
const handler = () => {
throw nonErrorString
}
const middleware = [buildMiddlewareTuple(handler)]
const onError = async (error: Error, c: Context) => {
return c.json({ message: error.message, cause: error.message }, 500)
}

const composed = compose(middleware, onError)
const context = await composed(c)
expect(context.res).not.toBeNull()
expect(context.res.status).toBe(500)
expect(await context.res.json()).toEqual({ message: nonErrorString, cause: nonErrorString })
expect(context.finalized).toBe(true)
})

it('Object (not string)', async () => {
const nonErrorObject = { body: 'Something went wrong' }
const handler = () => {
throw nonErrorObject
}
const middleware = [buildMiddlewareTuple(handler)]
const onError = async (error: Error, c: Context) => {
return c.json({ cause: error.cause }, 500)
}

const composed = compose(middleware, onError)
const context = await composed(c)
expect(context.res).not.toBeNull()
expect(context.res.status).toBe(500)
expect(await context.res.json()).toEqual({ cause: nonErrorObject })
expect(context.finalized).toBe(true)
})
})

describe('compose with Context - not finalized', () => {
const req = new Request('http://localhost/')
const c: Context = new Context(req)
Expand Down
10 changes: 7 additions & 3 deletions src/compose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,13 @@ export const compose = <E extends Env = Env>(
try {
res = await handler(context, () => dispatch(i + 1))
} catch (err) {
if (err instanceof Error && onError) {
context.error = err
res = await onError(err, context)
if (onError) {
const error =
err instanceof Error
? err
: new Error(typeof err === 'string' ? err : undefined, { cause: err })
context.error = error
res = await onError(error, context)
isError = true
} else {
throw err
Expand Down
Loading