fix(compose): do not handle the error in `compose` (#491)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(compose): do not handle the error in `compose` * tweak
authored by Yusuke Wada · committed by GitHub · parent 543fdba · Browse files · 6 files·+46 added−101 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+46 added−101 removed
- tests:+34 added−43 removed
- other:+12 added−58 removed
Provenance
- Commit
d3ff952- Tree
2968222- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
543fdba
6 files changed+46 added−101 removed
modified:deno_dist/compose.ts+5 added-24 removed
12234567895678912 unmodified lines2223242530312627283334353637383940414243444546474829303132332 unmodified linesimport { HonoContext } from './context.ts'import type { ErrorHandler, NotFoundHandler } from './hono.ts'import type { NotFoundHandler } from './hono.ts'
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C>( middleware: Function[], onError?: ErrorHandler, onNotFound?: NotFoundHandler) => {export const compose = <C>(middleware: Function[], onNotFound?: NotFoundHandler) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -1 return dispatch(0)12 unmodified lines } return context }
let res!: Response let isError: boolean = false const tmp = handler(context, () => dispatch(i + 1)) const res = tmp instanceof Promise ? await tmp : tmp
try { const tmp = handler(context, () => dispatch(i + 1)) res = tmp instanceof Promise ? await tmp : tmp } catch (err) { if (context instanceof HonoContext && onError) { if (err instanceof Error) { isError = true res = onError(err, context) } } if (!res) { throw err } }
if (res && context instanceof HonoContext && (!context.finalized || isError)) { if (res && context instanceof HonoContext && context.finalized === false) { context.res = res } return context }2 unmodified linesmodified:deno_dist/hono.ts+1 added-5 removed
201 unmodified lines202 const handlers = result ? result.handlers : [this.notFoundHandler]203 204 const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)205 206- const composed = compose<HonoContext<string, E>>(207- handlers,208- this.errorHandler,209- this.notFoundHandler210- )206+ const composed = compose<HonoContext<string, E>>(handlers, this.notFoundHandler)207 let context: HonoContext<string, E>208 try {209 context = await composed(c)210 if (!context.finalized) {27 unmodified linesmodified:src/compose.test.ts+11 added-43 removed
142 unmodified lines143 const middleware: Function[] = []144 145 const req = new Request('http://localhost/')146 const c: Context = new HonoContext(req)147- const onError = (_error: Error, c: Context) => {148- return c.text('onError', 500)149- }147 const onNotFound = (c: Context) => {148 return c.text('onNotFound', 404)149 }150 const mHandler = async (_c: Context, next: Function) => {2 unmodified lines153 154 middleware.push(mHandler)155 156 it('Should return 404 Response', async () => {160- const composed = compose<Context>(middleware, onError, onNotFound)157+ const composed = compose<Context>(middleware, onNotFound)158 const context = await composed(c)159 expect(context.res).not.toBeNull()160 expect(context.res.status).toBe(404)161 expect(await context.res.text()).toBe('onNotFound')5 unmodified lines167 const middleware: Function[] = []168 169 const req = new Request('http://localhost/')170 const c: Context = new HonoContext(req)174- const onError = (_error: Error, c: Context) => {175- return c.text('onError', 500)176- }171 const handler = (c: Context, _next: Function) => {172 return c.text('Hello')173 }174 const mHandler = async (c: Context, next: Function) => {4 unmodified lines179 middleware.push(mHandler)180 middleware.push(handler)181 182 it('Should return 401 Response', async () => {189- const composed = compose<Context>(middleware, onError)183+ const composed = compose<Context>(middleware)184 const context = await composed(c)185 expect(context.res).not.toBeNull()186 expect(context.res.status).toBe(401)187 expect(await context.res.text()).toBe('Not authorized')5 unmodified lines193 const middleware: Function[] = []194 195 const req = new Request('http://localhost/')196 const c: Context = new HonoContext(req)203- const onError = (_error: Error, c: Context) => {204- return c.text('onError', 500)205- }197 const handler = (c: Context) => {198 const message = c.req.header('x-custom') || 'blank'199 return c.text(message)200 }5 unmodified lines206 middleware.push(mHandler)207 middleware.push(handler)208 209 it('Should return 200 Response', async () => {219- const composed = compose<Context>(middleware, onError)210+ const composed = compose<Context>(middleware)211 const context = await composed(c)212 expect(context.res).not.toBeNull()213 expect(context.res.status).toBe(200)214 expect(await context.res.text()).toBe('foo')5 unmodified lines220 const middleware: Function[] = []221 222 const req = new Request('http://localhost/')223 const c: Context = new HonoContext(req)233- const onError = (_error: Error, c: Context) => {234- return c.text('onError', 500)235- }224 225 it('Error on handler', async () => {226 const handler = () => {227 throw new Error()228 }229 230 const mHandler = async (_c: Context, next: Function) => {231+ try {243- await next()232+ await next()233+ } catch {234+ return c.text('onError', 500)235+ }236 }237 238 middleware.push(mHandler)239 middleware.push(handler)240 249- const composed = compose<Context>(middleware, onError)241+ const composed = compose<Context>(middleware)242 const context = await composed(c)243 expect(context.res).not.toBeNull()244 expect(context.res.status).toBe(500)245 expect(await context.res.text()).toBe('onError')246 expect(context.finalized).toBe(true)247 })248 257- it('Error on middleware', async () => {258- const handler = (c: Context) => {259- return c.text('OK')260- }261-262- const mHandler = async () => {263- throw new Error()264- }265-266- middleware.push(mHandler)267- middleware.push(handler)268-269- const composed = compose<Context>(middleware, onError)270- const context = await composed(c)271- expect(c.res).not.toBeNull()272- expect(c.res.status).toBe(500)273- expect(await context.res.text()).toBe('onError')274- expect(context.finalized).toBe(true)275- })276-249 it('Run all the middlewares', async () => {250 const ctx: C = { req: {}, res: {} }251 const stack: number[] = []252 const middlewares = [17 unmodified lines270 })271 describe('compose with Context - not finalized', () => {272 const req = new Request('http://localhost/')273 const c: Context = new HonoContext(req)302-303- const onError = (_error: Error, c: Context) => {304- return c.text('onError', 500)305- }274 const onNotFound = (c: Context) => {275 return c.text('onNotFound', 404)276 }277 5 unmodified lines283 const mHandler2 = async () => {}284 285 middleware.push(mHandler)286 middleware.push(mHandler2)319- const composed = compose<Context>(middleware, onError, onNotFound)287+ const composed = compose<Context>(middleware, onNotFound)288 const context = await composed(c)289 expect(context.finalized).toBe(false)290 })291 5 unmodified lines297 const handler = async () => {}298 middleware2.push(mHandler3)299 middleware2.push(handler)300 333- const composed = compose<Context>(middleware2, onError, onNotFound)301+ const composed = compose<Context>(middleware2, onNotFound)302 const context = await composed(c)303 expect(context.finalized).toBe(false)304 })305 })360 unmodified linesmodified:src/compose.ts+5 added-24 removed
12234567895678912 unmodified lines2223242530312627283334353637383940414243444546474829303132332 unmodified linesimport { HonoContext } from './context'import type { ErrorHandler, NotFoundHandler } from './hono'import type { NotFoundHandler } from './hono'
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <C>( middleware: Function[], onError?: ErrorHandler, onNotFound?: NotFoundHandler) => {export const compose = <C>(middleware: Function[], onNotFound?: NotFoundHandler) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -1 return dispatch(0)12 unmodified lines } return context }
let res!: Response let isError: boolean = false const tmp = handler(context, () => dispatch(i + 1)) const res = tmp instanceof Promise ? await tmp : tmp
try { const tmp = handler(context, () => dispatch(i + 1)) res = tmp instanceof Promise ? await tmp : tmp } catch (err) { if (context instanceof HonoContext && onError) { if (err instanceof Error) { isError = true res = onError(err, context) } } if (!res) { throw err } }
if (res && context instanceof HonoContext && (!context.finalized || isError)) { if (res && context instanceof HonoContext && context.finalized === false) { context.res = res } return context }2 unmodified linesmodified:src/hono.test.ts+23 added
552 unmodified lines553 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')554 })555 })556 557+describe('Error handling in middleware', () => {558+ const app = new Hono()559+560+ app.get('/handle-error-in-middleware', async (c, next) => {561+ try {562+ await next()563+ } catch {564+ c.res = c.text('Handle the error in middleware', 500)565+ }566+ })567+568+ app.get('/handle-error-in-middleware', () => {569+ console.log('throw new Error')570+ throw new Error('This is Error')571+ })572+573+ it('Should handle the error in middleware', async () => {574+ const res = await app.request('https://example.com/handle-error-in-middleware')575+ expect(res.status).toBe(500)576+ expect(await res.text()).toBe('Handle the error in middleware')577+ })578+})579+580 describe('Request methods with custom middleware', () => {581 const app = new Hono()582 583 app.use('*', async (c, next) => {476 unmodified linesmodified:src/hono.ts+1 added-5 removed
201 unmodified lines202 const handlers = result ? result.handlers : [this.notFoundHandler]203 204 const c = new HonoContext<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)205 206- const composed = compose<HonoContext<string, E>>(207- handlers,208- this.errorHandler,209- this.notFoundHandler210- )206+ const composed = compose<HonoContext<string, E>>(handlers, this.notFoundHandler)207 let context: HonoContext<string, E>208 try {209 context = await composed(c)210 if (!context.finalized) {27 unmodified lines