feat: use added app's errorHandler with comose() (#874)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor(compose): Swapped the order of onNotFound and onError in the compose() argument. * feat: use added app's errorHandler * chore: denoify
authored by Taku Amano · committed by GitHub · parent 229228a · Browse files · 6 files·+173 added−30 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+173 added−30 removed
- tests:+129 added−4 removed
- other:+44 added−26 removed
Provenance
- Commit
c169a41- Tree
34cbf5f- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
229228a
6 files changed+173 added−30 removed
modified:deno_dist/compose.ts+2 added-2 removed
7 unmodified lines891011121312131415161759 unmodified lines7 unmodified lines
// 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>, onError?: ErrorHandler<E> onError?: ErrorHandler<E>, onNotFound?: NotFoundHandler<E>) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -159 unmodified linesmodified:deno_dist/hono.ts+20 added-11 removed
59 unmodified lines60 method: string61 handler: Handler<P, E, S>62 }63 64+const notFoundHandler = <E extends Partial<Environment>>(c: Context<string, E>) => {65+ return c.text('404 Not Found', 404)66+}67+68+const errorHandler = <E extends Partial<Environment>>(err: Error, c: Context<string, E>) => {69+ console.trace(err)70+ const message = 'Internal Server Error'71+ return c.text(message, 500)72+}73+74 export class Hono<75 E extends Partial<Environment> = Environment,76 P extends string = string,77 S = unknown34 unmodified lines112 113 Object.assign(this, init)114 }115 106- private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {107- return c.text('404 Not Found', 404)108- }116+ private notFoundHandler: NotFoundHandler<E> = notFoundHandler117+ private errorHandler: ErrorHandler<E> = errorHandler118 110- private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {111- console.trace(err)112- const message = 'Internal Server Error'113- return c.text(message, 500)114- }115-119 // eslint-disable-next-line @typescript-eslint/no-explicit-any120 route(path: string, app?: Hono<any>) {121 this._tempPath = path122 if (app) {123 app.routes.map((r) => {121- this.addRoute(r.method, r.path, r.handler as unknown as Handler<P, E, S>)124+ const handler = (125+ app.errorHandler === errorHandler126+ ? r.handler127+ : async (...args) =>128+ (await compose<Context<P, E>, E>([r.handler], app.errorHandler)(...args)).res129+ ) as Handler<P, E, S>130+ this.addRoute(r.method, r.path, handler)131 })132 this._tempPath = ''133 }134 return this109 unmodified lines244 })()245 }246 247 const handlers = result ? result.handlers : [this.notFoundHandler]239- const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)248+ const composed = compose<Context<P, E>, E>(handlers, this.errorHandler, this.notFoundHandler)249 250 return (async () => {251 try {252 // eslint-disable-next-line @typescript-eslint/no-explicit-any27 unmodified linesmodified:src/compose.test.ts+4 added-4 removed
153 unmodified lines154 155 middleware.push(mHandler)156 157 it('Should return 404 Response', async () => {158- const composed = compose<Context>(middleware, onNotFound)158+ const composed = compose<Context>(middleware, undefined, onNotFound)159 const context = await composed(c)160 expect(context.res).not.toBeNull()161 expect(context.res.status).toBe(404)162 expect(await context.res.text()).toBe('onNotFound')74 unmodified lines237 238 const onNotFound = (c: Context) => c.text('NotFound', 404)239 const onError = (_error: Error, c: Context) => c.text('onError', 500)240 241- const composed = compose<Context>(middleware, onNotFound, onError)241+ const composed = compose<Context>(middleware, onError, onNotFound)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')37 unmodified lines283 const mHandler2 = async () => {}284 285 middleware.push(mHandler)286 middleware.push(mHandler2)287- const composed = compose<Context>(middleware, onNotFound)287+ const composed = compose<Context>(middleware, undefined, 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 301- const composed = compose<Context>(middleware2, onNotFound)301+ const composed = compose<Context>(middleware2, undefined, onNotFound)302 const context = await composed(c)303 expect(context.finalized).toBe(false)304 })305 })357 unmodified linesmodified:src/compose.ts+2 added-2 removed
7 unmodified lines891011121312131415161759 unmodified lines7 unmodified lines
// 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>, onError?: ErrorHandler<E> onError?: ErrorHandler<E>, onNotFound?: NotFoundHandler<E>) => { const middlewareLength = middleware.length return (context: C, next?: Function) => { let index = -159 unmodified linesmodified:src/hono.test.ts+125 added
933 unmodified lines934 expect(res.status).toBe(200)935 expect(await res.text()).toBe('book 123')936 })937 })938+939+ describe('onError', () => {940+ const app = new Hono()941+ const sub = new Hono()942+943+ app.use('*', async (c, next) => {944+ await next()945+ if (c.req.query('app-error')) {946+ throw new Error('This is Error')947+ }948+ })949+950+ app.onError((err, c) => {951+ return c.text('onError by app', 500)952+ })953+954+ sub.get('/ok', (c) => {955+ return c.text('ok')956+ })957+958+ sub.get('/error', () => {959+ throw new Error('This is Error')960+ })961+962+ sub.onError((err, c) => {963+ return c.text('onError by sub', 500)964+ })965+966+ app.route('/sub', sub)967+968+ it('should be handled by app', async () => {969+ const res = await app.request('https://example.com/sub/ok?app-error=1')970+ expect(res.status).toBe(500)971+ expect(await res.text()).toBe('onError by app')972+ })973+974+ it('should be handled by sub', async () => {975+ const res = await app.request('https://example.com/sub/error')976+ expect(res.status).toBe(500)977+ expect(await res.text()).toBe('onError by sub')978+ })979+ })980+981+ describe('onError for a single handler', () => {982+ const app = new Hono()983+ const sub = new Hono()984+985+ sub.get('/ok', (c) => c.text('OK'))986+987+ sub.get('/error', () => {988+ throw new Error('This is Error')989+ })990+991+ sub.onError((err, c) => {992+ return c.text('onError by sub', 500)993+ })994+995+ app.route('/sub', sub)996+997+ it('ok', async () => {998+ const res = await app.request('https://example.com/sub/ok')999+ expect(res.status).toBe(200)1000+ })1001+1002+ it('error', async () => {1003+ const res = await app.request('https://example.com/sub/error')1004+ expect(res.status).toBe(500)1005+ expect(await res.text()).toBe('onError by sub')1006+ })1007+ })1008+1009+ describe('notFound', () => {1010+ const app = new Hono()1011+ const sub = new Hono()1012+1013+ app.get('/explicit-404', async (c) => {1014+ c.header('explicit', '1')1015+ })1016+1017+ app.notFound((c) => {1018+ return c.text('404 Not Found by app', 404)1019+ })1020+1021+ sub.get('/ok', (c) => {1022+ return c.text('ok')1023+ })1024+1025+ sub.get('/explicit-404', async (c) => {1026+ c.header('explicit', '1')1027+ })1028+1029+ sub.notFound((c) => {1030+ return c.text('404 Not Found by sub', 404)1031+ })1032+1033+ app.route('/sub', sub)1034+1035+ it('/explicit-404 should be handled on app', async () => {1036+ const res = await app.request('https://example.com/explicit-404')1037+ expect(res.status).toBe(404)1038+ expect(res.headers.get('explicit')).toBe('1')1039+ expect(await res.text()).toBe('404 Not Found by app')1040+ })1041+1042+ it('/sub/explicit-404 should be handled on app', async () => {1043+ const res = await app.request('https://example.com/sub/explicit-404')1044+ expect(res.status).toBe(404)1045+ expect(res.headers.get('explicit')).toBe('1')1046+ expect(await res.text()).toBe('404 Not Found by app')1047+ })1048+1049+ it('/implicit-404 should be handled by app', async () => {1050+ const res = await app.request('https://example.com/implicit-404')1051+ expect(res.status).toBe(404)1052+ expect(res.headers.get('explicit')).toBe(null)1053+ expect(await res.text()).toBe('404 Not Found by app')1054+ })1055+1056+ it('/sub/implicit-404 should be handled by sub', async () => {1057+ const res = await app.request('https://example.com/sub/implicit-404')1058+ expect(res.status).toBe(404)1059+ expect(res.headers.get('explicit')).toBe(null)1060+ expect(await res.text()).toBe('404 Not Found by app')1061+ })1062+ })1063 })1064 1065 describe('Using other methods with `app.on`', () => {1066 it('Should handle PURGE method with StaticRouter', async () => {504 unmodified linesmodified:src/hono.ts+20 added-11 removed
59 unmodified lines60 method: string61 handler: Handler<P, E, S>62 }63 64+const notFoundHandler = <E extends Partial<Environment>>(c: Context<string, E>) => {65+ return c.text('404 Not Found', 404)66+}67+68+const errorHandler = <E extends Partial<Environment>>(err: Error, c: Context<string, E>) => {69+ console.trace(err)70+ const message = 'Internal Server Error'71+ return c.text(message, 500)72+}73+74 export class Hono<75 E extends Partial<Environment> = Environment,76 P extends string = string,77 S = unknown34 unmodified lines112 113 Object.assign(this, init)114 }115 106- private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {107- return c.text('404 Not Found', 404)108- }116+ private notFoundHandler: NotFoundHandler<E> = notFoundHandler117+ private errorHandler: ErrorHandler<E> = errorHandler118 110- private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {111- console.trace(err)112- const message = 'Internal Server Error'113- return c.text(message, 500)114- }115-119 // eslint-disable-next-line @typescript-eslint/no-explicit-any120 route(path: string, app?: Hono<any>) {121 this._tempPath = path122 if (app) {123 app.routes.map((r) => {121- this.addRoute(r.method, r.path, r.handler as unknown as Handler<P, E, S>)124+ const handler = (125+ app.errorHandler === errorHandler126+ ? r.handler127+ : async (...args) =>128+ (await compose<Context<P, E>, E>([r.handler], app.errorHandler)(...args)).res129+ ) as Handler<P, E, S>130+ this.addRoute(r.method, r.path, handler)131 })132 this._tempPath = ''133 }134 return this109 unmodified lines244 })()245 }246 247 const handlers = result ? result.handlers : [this.notFoundHandler]239- const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)248+ const composed = compose<Context<P, E>, E>(handlers, this.errorHandler, this.notFoundHandler)249 250 return (async () => {251 try {252 // eslint-disable-next-line @typescript-eslint/no-explicit-any27 unmodified lines