fix(compose): don't throw Error; set error response into `c.res` (#576)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 61e24b0 · Browse files · 8 files·+65 added−29 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+65 added−29 removed
- tests:+13 added−13 removed
- other:+52 added−16 removed
Provenance
- Commit
39f896a- Tree
2be9889- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
61e24b0
8 files changed+65 added−29 removed
modified:deno_dist/compose.ts+19 added-7 removed
12234567891011121213141516177 unmodified lines252627282930313233343536343536373738394041424344454647484950515241535455565710 unmodified linesimport { HonoContext } from './context.ts'import type { Environment, NotFoundHandler } from './hono.ts'import type { Environment, NotFoundHandler, ErrorHandler } from './hono.ts'
interface ComposeContext { finalized: boolean res: any}
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>( middleware: Function[], onNotFound?: NotFoundHandler<E> onNotFound?: NotFoundHandler<E>, onError?: ErrorHandler<E>) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -17 unmodified lines index = i if (i === middlewareLength && next) handler = next
let res let isError = false
if (!handler) { if (context instanceof HonoContext && context.finalized === false && onNotFound) { res = onNotFound(context) } } else { try { res = handler(context, () => { const dispatchRes = dispatch(i + 1) return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes) }) res = handler(context, () => { const dispatchRes = dispatch(i + 1) return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes) }) } catch (err) { if (err instanceof Error && context instanceof HonoContext && onError) { context.error = err res = onError(err, context) isError = true } else { throw err } } }
if (!(res instanceof Promise)) { if (res && context.finalized === false) { if (res && (context.finalized === false || isError)) { context.res = res } return context } else {10 unmodified linesmodified:deno_dist/context.ts+2 added
21 unmodified lines22 env: E['Bindings']23 event: FetchEvent24 executionCtx: ExecutionContext25 finalized: boolean26+ error: Error | undefined27 28 get res(): Response29 set res(_res: Response)30 header: (name: string, value: string, options?: { append?: boolean }) => void27 unmodified lines58 {59 req: Request<RequestParamKeyType, D>60 env: E['Bindings']61 finalized: boolean62+ error: Error | undefined = undefined63 64 _status: StatusCode = 20065 private _executionCtx: FetchEvent | ExecutionContext | undefined66 private _pretty: boolean = false172 unmodified linesmodified:deno_dist/hono.ts+5 added-1 removed
247 unmodified lines248 })()249 }250 251 const handlers = result ? result.handlers : [this.notFoundHandler]252- const composed = compose<HonoContext<string, E>, E>(handlers, this.notFoundHandler)252+ const composed = compose<HonoContext<string, E>, E>(253+ handlers,254+ this.notFoundHandler,255+ this.errorHandler256+ )257 258 return (async () => {259 try {260 const tmp = composed(c)26 unmodified linesmodified:src/compose.test.ts+5 added-6 removed
228 unmodified lines229 throw new Error()230 }231 232 const mHandler = async (_c: Context, next: Function) => {233- try {234- await next()233+ await next()235- } catch {236- return c.text('onError', 500)237- }234 }235 236 middleware.push(mHandler)237 middleware.push(handler)238 239+ const onNotFound = (c: Context) => c.text('NotFound', 404)240+ const onError = (_error: Error, c: Context) => c.text('onError', 500)241+243- const composed = compose<Context>(middleware)242+ const composed = compose<Context>(middleware, onNotFound, onError)243 const context = await composed(c)244 expect(context.res).not.toBeNull()245 expect(context.res.status).toBe(500)246 expect(await context.res.text()).toBe('onError')420 unmodified linesmodified:src/compose.ts+19 added-7 removed
12234567891011121213141516177 unmodified lines252627282930313233343536343536373738394041424344454647484950515241535455565710 unmodified linesimport { HonoContext } from './context'import type { Environment, NotFoundHandler } from './hono'import type { Environment, NotFoundHandler, ErrorHandler } from './hono'
interface ComposeContext { finalized: boolean res: any}
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>( middleware: Function[], onNotFound?: NotFoundHandler<E> onNotFound?: NotFoundHandler<E>, onError?: ErrorHandler<E>) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -17 unmodified lines index = i if (i === middlewareLength && next) handler = next
let res let isError = false
if (!handler) { if (context instanceof HonoContext && context.finalized === false && onNotFound) { res = onNotFound(context) } } else { try { res = handler(context, () => { const dispatchRes = dispatch(i + 1) return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes) }) res = handler(context, () => { const dispatchRes = dispatch(i + 1) return dispatchRes instanceof Promise ? dispatchRes : Promise.resolve(dispatchRes) }) } catch (err) { if (err instanceof Error && context instanceof HonoContext && onError) { context.error = err res = onError(err, context) isError = true } else { throw err } } }
if (!(res instanceof Promise)) { if (res && context.finalized === false) { if (res && (context.finalized === false || isError)) { context.res = res } return context } else {10 unmodified linesmodified:src/context.ts+2 added
21 unmodified lines22 env: E['Bindings']23 event: FetchEvent24 executionCtx: ExecutionContext25 finalized: boolean26+ error: Error | undefined27 28 get res(): Response29 set res(_res: Response)30 header: (name: string, value: string, options?: { append?: boolean }) => void27 unmodified lines58 {59 req: Request<RequestParamKeyType, D>60 env: E['Bindings']61 finalized: boolean62+ error: Error | undefined = undefined63 64 _status: StatusCode = 20065 private _executionCtx: FetchEvent | ExecutionContext | undefined66 private _pretty: boolean = false172 unmodified linesmodified:src/hono.test.ts+8 added-7 removed
561 unmodified lines562 describe('Error handling in middleware', () => {563 const app = new Hono()564 565 app.get('/handle-error-in-middleware', async (c, next) => {566- try {567- await next()568- } catch {569- c.res = c.text('Handle the error in middleware', 500)566+ await next()567+ if (c.error) {568+ const message = c.error.message569+ c.res = c.text(`Handle the error in middleware, original message is ${message}`, 500)570 }571 })572 573 app.get('/handle-error-in-middleware', () => {574- console.log('throw new Error')575- throw new Error('This is Error')574+ throw new Error('Error message')575 })576 577 it('Should handle the error in middleware', async () => {578 const res = await app.request('https://example.com/handle-error-in-middleware')579 expect(res.status).toBe(500)581- expect(await res.text()).toBe('Handle the error in middleware')580+ expect(await res.text()).toBe(581+ 'Handle the error in middleware, original message is Error message'582+ )583 })584 })585 586 describe('Request methods with custom middleware', () => {530 unmodified linesmodified:src/hono.ts+5 added-1 removed
247 unmodified lines248 })()249 }250 251 const handlers = result ? result.handlers : [this.notFoundHandler]252- const composed = compose<HonoContext<string, E>, E>(handlers, this.notFoundHandler)252+ const composed = compose<HonoContext<string, E>, E>(253+ handlers,254+ this.notFoundHandler,255+ this.errorHandler256+ )257 258 return (async () => {259 try {260 const tmp = composed(c)26 unmodified lines