feat: Error handling (#48)
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 a22a0eb · Browse files · 4 files·+67 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+67 added−5 removed
- tests:+26 added−1 removed
- other:+41 added−4 removed
Provenance
- Commit
7c92d55- Tree
9a604f9- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
a22a0eb
4 files changed+67 added−5 removed
modified:example/basic/index.js+16 added-1 removed
36 unmodified lines37383940414243444546474849505152535434 unmodified lines89909192839394959697989910010110236 unmodified lines const ms = Date.now() - start await c.res.headers.append('X-Response-Time', `${ms}ms`)})
// Handle errorapp.use('*', async (c, next) => { try { await next() } catch (err) { console.error(`${err}`) c.res = new Response('Custom Error Message', { status: 500 }) }})
// Routingapp.get('/', (c) => c.text('Hono!!'))// Use Response object directlyapp.get('/hello', () => new Response('This is /hello'))34 unmodified linesapp.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))
app.post('/form', async (ctx) => { return ctx.json(ctx.req.parsedBody || {})//return new Response('ok /form') //return new Response('ok /form')})
// Throw Errorapp.get('/error', () => { throw Error('Error has occurred')})
// addEventListenerapp.fire()modified:src/hono.ts+12 added-3 removed
119 unmodified lines120 async matchRoute(method: string, path: string): Promise<Result<Handler[]>> {121 return this.router.match(method, path)122 }123 124- async dispatch(request: Request, env?: Env, event?: FetchEvent) {124+ async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {125 const [method, path] = [request.method, getPathFromURL(request.url)]126 127 const result = await this.matchRoute(method, path)128 30 unmodified lines159 return c.res160 }161 162 async handleEvent(event: FetchEvent): Promise<Response> {163- return this.dispatch(event.request, {}, event)163+ return this.dispatch(event.request, {}, event).catch((err) => {164+ return this.onError(err)165+ })166 }167 168 async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {167- return this.dispatch(request, env, event)169+ return this.dispatch(request, env, event).catch((err) => {170+ return this.onError(err)171+ })172 }173 174 fire() {175 addEventListener('fetch', (event: FetchEvent): void => {176 event.respondWith(this.handleEvent(event))177 })178 }179 180+ onError(err: any) {181+ console.error(err)182+ return new Response('Internal Server Error', { status: 500 })183+ }184+185 notFound() {186 return new Response('Not Found', { status: 404 })187 }188 }modified:test/hono.test.ts+26 added-1 removed
205 unmodified lines206 it('Absolute URL', async () => {207 const req = new Request('https://example.com/redirect')208 const res = await app.dispatch(req)209 expect(res.status).toBe(302)210- expect(await res.headers.get('Location')).toBe('https://example.com/')210+ expect(res.headers.get('Location')).toBe('https://example.com/')211 })212 })213+214+describe('Error handle', () => {215+ const app = new Hono()216+217+ app.get('/error', () => {218+ throw 'This is Error'219+ })220+221+ app.use('*', async (c, next) => {222+ try {223+ await next()224+ } catch (err) {225+ c.res = new Response('Custom Error Message', { status: 500 })226+ c.res.headers.append('debug', String(err))227+ }228+ })229+230+ it('Custom Error Message', async () => {231+ const req = new Request('https://example.com/error')232+ const res = await app.dispatch(req)233+ expect(res.status).toBe(500)234+ expect(await res.text()).toBe('Custom Error Message')235+ expect(res.headers.get('debug')).toBe('This is Error')236+ })237+})modified:README.md+13 added
176 unmodified lines177 }178 })179 ```180 181+### Handling Error182+183+```js184+app.use('*', async (c, next) => {185+ try {186+ await next()187+ } catch (err) {188+ console.error(`${err}`)189+ c.res = new Response('Custom Error Message', { status: 500 })190+ }191+})192+```193+194 ### Complex Pattern195 196 You can also do this:197 236 unmodified lines