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
Provenance
- Commit
9de6328- Tree
4ee279f- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
49fedca
5 files changed+43 added−54 removed
modified:src/middleware/logger/logger.ts+1 added-6 removed
58 unmodified lines5960616263646365666768646566673 unmodified lines58 unmodified lines log(fn, LogPrefix.Incoming, method, path)
const start = Date.now()
try { await next() await next() } catch (e) { log(fn, LogPrefix.Error, method, path, c.res.status || 500, time(start)) throw e }
const len = parseFloat(c.res.headers.get('Content-Length')) const contentLength = isNaN(len) ? '0' : len < 1024 ? `${len}b` : `${len / 1024}kB`
3 unmodified linesmodified:src/compose.ts+8 added-2 removed
1232456785 unmodified lines14151617181920162122232425263 unmodified linesimport { Context } from './context'
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <T>(middleware: Function[]) => {export const compose = <T>(middleware: Function[], onError?: Function) => { const errors: Error[] = [] return function (context: T, next?: Function) { let index = -1 return dispatch(0)5 unmodified lines if (!fn) return Promise.resolve() try { return Promise.resolve(fn(context, dispatch.bind(null, i + 1))).catch((e) => { errors.push(e) if (onError && context instanceof Context) { context.res = onError(errors[0], context) } else { throw errors[0] // XXX throw errors[0] } }) } catch (err) { return Promise.reject(err) }3 unmodified linesmodified:src/hono.ts+8 added-15 removed
179 unmodified lines180 }181 182 middleware.push(wrappedHandler)183 184- 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)187 188 await composed(c)1 unmodified line190 return c.res191 }192 193 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 }196 197 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 }200 201 fire() {202 addEventListener('fetch', (event: FetchEvent): void => {203 event.respondWith(this.handleEvent(event))204 })205 }206 207+ // 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 }213 214+ // Default 404 not found Response215 notFound(c: Context) {216 const message = 'Not Found'217 return c.text(message, 404)218 }1 unmodified linemodified:test/hono.test.ts+15 added-17 removed
311 unmodified lines312 describe('Error handle', () => {313 const app = new Hono()314 315 app.get('/error', () => {316- throw 'This is Error'316+ throw new Error('This is Error')317 })318 319- 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 })322 323+ app.onError = (err, c) => {324+ c.header('debug', err.message)325+ return c.text('Custom Error Message', 500)326+ }327+328 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- })334 336- // 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 })342 343 describe('Request methods with custom middleware', () => {39 unmodified linesmodified:README.md+11 added-14 removed
179 unmodified lines180 181 app.get('/message/hello', (c) => c.text('Hello Middleware!'))182 ```183 184-### Handling Error185-186-```js187-app.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-```196-184 ## Context185 186 To handle Request and Reponse, you can use Context object:187 130 unmodified lines318 ...319 })320 ```321 335-## `404 Not Found` Response322+## Not Found323 324 If you want, you can set the default `404 Not Found` Response:325 326 ```js1 unmodified line328 return c.text('This is default 404 Not Found', 404)329 }330 ```331 332+## Error handling333+334+You can handle errors in your way:335+336+```js337+app.onError = (err, c) => {338+ return c.text(`This is error message: ${err.mssage}`, 500)339+}340+```341+342 ## fire343 344 `app.fire()` do:345 126 unmodified lines