Skip to content
Myr

feat: `app.onError` for handling error (#111)

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 49fedca · Browse files · 5 files+43 added−54 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+43 added−54 removed

  • tests:+15 added−17 removed
  • other:+28 added−37 removed

5 files+43 added−54 removed

modified:src/middleware/logger/logger.ts+1 added-6 removed
modified:src/compose.ts+8 added-2 removed
modified:src/hono.ts+8 added-15 removed
179 unmodified lines
180 }181182 middleware.push(wrappedHandler)183184 const composed = compose<Context>(middleware)184 const composed = compose<Context>(middleware, this.onError)185 const c = new Context(request, { env: env, event: event, res: null })186 c.notFound = () => this.notFound(c)187188 await composed(c)
1 unmodified line
190 return c.res191 }192193 async handleEvent(event: FetchEvent): Promise<Response> {194 return this.dispatch(event.request, {}, event).catch((err: Error) => {195 return this.onError(err)196 })194 return this.dispatch(event.request, {}, event)195 }196197 async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {200 return this.dispatch(request, env, event).catch((err: Error) => {201 return this.onError(err)202 })198 return this.dispatch(request, env, event)199 }200201 fire() {202 addEventListener('fetch', (event: FetchEvent): void => {203 event.respondWith(this.handleEvent(event))204 })205 }206207 // Default error Response211 onError(err: Error) {212 console.error(`${err}`)208 onError(err: Error, c: Context) {209 console.error(`${err.message}`)210 const message = 'Internal Server Error'214 return new Response(message, {215 status: 500,216 headers: {217 'Content-Length': message.length.toString(),218 },219 })211 return c.text(message, 500)212 }213214 // Default 404 not found Response215 notFound(c: Context) {216 const message = 'Not Found'217 return c.text(message, 404)218 }
1 unmodified line
modified:test/hono.test.ts+15 added-17 removed
311 unmodified lines
312describe('Error handle', () => {313 const app = new Hono()314315 app.get('/error', () => {316 throw 'This is Error'316 throw new Error('This is Error')317 })318319 app.use('/error', async (c, next) => {320 try {321 await next()322 } catch (err) {323 c.res = new Response('Custom Error Message', { status: 500 })324 c.res.headers.append('debug', String(err))325 }319 app.use('/error-middleware', async () => {320 throw new Error('This is Middleware Error')321 })322323 app.onError = (err, c) => {324 c.header('debug', err.message)325 return c.text('Custom Error Message', 500)326 }327328 it('Custom Error Message', async () => {329 const req = new Request('https://example.com/error')330 const res = await app.dispatch(req)329 let req = new Request('https://example.com/error')330 let res = await app.dispatch(req)331 expect(res.status).toBe(500)332 expect(await res.text()).toBe('Custom Error Message')333 expect(res.headers.get('debug')).toBe('This is Error')334 })334336 // eslint-disable-next-line @typescript-eslint/ban-ts-comment337 // @ts-ignore338 app.get('/text', () => 'text')339 it('If return not Reponse object', async () => {340 const req = new Request('https://example.com/text')341 expect(app.dispatch(req)).rejects.toThrowError(TypeError)335 req = new Request('https://example.com/error-middleware')336 res = await app.dispatch(req)337 expect(res.status).toBe(500)338 expect(await res.text()).toBe('Custom Error Message')339 expect(res.headers.get('debug')).toBe('This is Middleware Error')340 })341})342343describe('Request methods with custom middleware', () => {
39 unmodified lines
modified:README.md+11 added-14 removed
179 unmodified lines
180181app.get('/message/hello', (c) => c.text('Hello Middleware!'))182```183184### Handling Error185186```js187app.use('*', async (c, next) => {188 try {189 await next()190 } catch (err) {191 console.error(`${err}`)192 c.res = c.text('Custom Error Message', { status: 500 })193 }194})195```196184## Context185186To handle Request and Reponse, you can use Context object:187
130 unmodified lines
318 ...319})320```321335## `404 Not Found` Response322## Not Found323324If you want, you can set the default `404 Not Found` Response:325326```js
1 unmodified line
328 return c.text('This is default 404 Not Found', 404)329}330```331332## Error handling333334You can handle errors in your way:335336```js337app.onError = (err, c) => {338 return c.text(`This is error message: ${err.mssage}`, 500)339}340```341342## fire343344`app.fire()` do:345
126 unmodified lines