Skip to content
Myr

feat: `app.notFound()` and `app.onError` (#117)

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 a66296b · Browse files · 5 files+77 added−64 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+77 added−64 removed

  • tests:+8 added−14 removed
  • other:+69 added−50 removed

5 files+77 added−64 removed

modified:examples/basic/index.js+9 added-8 removed
modified:src/compose.ts+2 added-1 removed
modified:src/hono.test.ts+8 added-14 removed
14 unmodified lines
15 c.status(201)16 return c.html('<h1>Hono!!!</h1>')17 })1819 app.notFound = () => {20 return new Response('not found', {21 status: 404,22 })23 }2419 it('GET /hello is ok', async () => {20 const req = new Request('http://localhost/hello')21 const res = await app.dispatch(req)22 expect(res).not.toBeNull()
236 unmodified lines
259 expect(res.headers.get('x-message-2')).toBe('custom-header-2')260 })261})262269describe('404 Not Found', () => {263describe('Not Found', () => {264 const app = new Hono()265272 app.notFound = (c) => {266 app.notFound((c) => {267 return c.text('Custom 404 Not Found', 404)274 }268 })269270 app.get('/hello', (c) => {271 return c.text('hello')272 })
40 unmodified lines
313 app.use('/error-middleware', async () => {314 throw new Error('This is Middleware Error')315 })316323 app.onError = (err, c) => {324 c.header('debug', err.message)317 app.onError((err, c) => {318 c.header('x-debug', err.message)319 return c.text('Custom Error Message', 500)326 }320 })321322 it('Custom Error Message', async () => {323 let req = new Request('https://example.com/error')324 let res = await app.dispatch(req)325 expect(res.status).toBe(500)326 expect(await res.text()).toBe('Custom Error Message')333 expect(res.headers.get('debug')).toBe('This is Error')327 expect(res.headers.get('x-debug')).toBe('This is Error')328329 req = new Request('https://example.com/error-middleware')330 res = await app.dispatch(req)331 expect(res.status).toBe(500)332 expect(await res.text()).toBe('Custom Error Message')339 expect(res.headers.get('debug')).toBe('This is Middleware Error')333 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')334 })335})336337describe('Request methods with custom middleware', () => {
39 unmodified lines
modified:src/hono.ts+26 added-16 removed
19 unmodified lines
20 c: Context<RequestParamKeyType>,21 next?: Function22) => Response | Promise<Response>23export type MiddlewareHandler = (c: Context, next: Function) => Promise<void>24export type NotFoundHandler = (c: Context) => Response25export type ErrorHandler = (err: Error, c: Context) => Response2627// eslint-disable-next-line @typescript-eslint/no-unused-vars28type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`29 ? Name
21 unmodified lines
51 this.middlewareRouters = []52 this.tempPath = null53 }5455 notFoundHandler: NotFoundHandler = (c: Context) => {56 const message = '404 Not Found'57 return c.text(message, 404)58 }5960 errorHandler: ErrorHandler = (err: Error, c: Context) => {61 console.error(`${err.message}`)62 const message = 'Internal Server Error'63 return c.text(message, 500)64 }6566 /* HTTP METHODS */67 get<Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>): Hono68 get(path: string, handler: Handler): Hono {69 return this.addRoute('get', path, handler)
50 unmodified lines
120 router.add(METHOD_NAME_OF_ALL, path, middleware)121 this.middlewareRouters.push(router)122 }123124 onError(handler: ErrorHandler): Hono {125 this.errorHandler = handler126 return this127 }128129 notFound(handler: NotFoundHandler): Hono {130 this.notFoundHandler = handler131 return this132 }133134 // addRoute('get', '/', handler)135 addRoute(method: string, path: string, handler: Handler): Hono {136 method = method.toUpperCase()137 if (this.tempPath) {
26 unmodified lines
164 const url = new URL(c.req.url)165 return url.searchParams.get(key)166 }167145 const handler = result ? result.handler : this.notFound168 const handler = result ? result.handler : this.notFoundHandler169170 const middleware = []171172 for (const mr of this.middlewareRouters) {
13 unmodified lines
186 }187188 middleware.push(wrappedHandler)189167 const composed = compose<Context>(middleware, this.onError)190 const composed = compose<Context>(middleware, this.errorHandler)191 const c = new Context(request, { env: env, event: event, res: null })169 c.notFound = () => this.notFound(c)192 c.notFound = () => this.notFoundHandler(c)193194 const context = await composed(c)195196 return context.res
11 unmodified lines
208 addEventListener('fetch', (event: FetchEvent): void => {209 event.respondWith(this.handleEvent(event))210 })211 }189190 // Default error Response191 onError(err: Error, c: Context) {192 console.error(`${err.message}`)193 const message = 'Internal Server Error'194 return c.text(message, 500)195 }196197 // Default 404 not found Response198 notFound(c: Context) {199 const message = 'Not Found'200 return c.text(message, 404)201 }212}
modified:README.md+32 added-25 removed
69 unmodified lines
70- app.**HTTP_METHOD**(path, handler)71- app.**all**(path, handler)72- app.**route**(path)73- app.**use**(path, middleware)74- app.**notFound**(handler)75- app.**onError**(err, handler)76- app.**fire**()77- app.**fetch**(request, env, event)7879## Routing
47 unmodified lines
127```128129### no strict130129If `strict` is set `false`, `/hello`and`/hello/` are treated the same. Default is `true`.131If `strict` is set false, `/hello`and`/hello/` are treated the same.132133```js132const app = new Hono({ strict: false })134const app = new Hono({ strict: false }) // Default is true135136app.get('/hello', (c) => c.text('/hello or /hello/'))137```138
50 unmodified lines
189190app.get('/message/hello', (c) => c.text('Hello Middleware!'))191```192193## Error194195### Not Found196197`app.notFound` for customizing Not Found Response.198199```js200app.notFound((c) => {201 return c.text('Custom 404 Message', 404)202})203```204205### Error Handling206207`app.onError` handle the error and return the customized Response.208209```js210app.onError((err, c) => {211 console.error(`${err}`)212 return c.text('Custom Error Message', 500)213})214```215216## Context217218To handle Request and Reponse, you can use Context object.219
28 unmodified lines
248### Shortcuts for Response249250```js251app.get('/welcome', (c) => {252 // Set headers253 c.header('X-Message', 'Hello!')254 c.header('Content-Type', 'text/plain')255 // Set HTTP status code256 c.status(201)230257 // Return the response body258 return c.body('Thank you for comming')259})260```261
42 unmodified lines
304```305306### c.notFound()307281Return the default `404 Not Found` Response.308Return the `404 Not Found` Response.309310```js311app.get('/notfound', (c) => {312 return c.notFound()
40 unmodified lines
353 ...354})355```356330## Not Found331332You can write the default `404 Not Found` Response.333334```js335app.notFound = (c) => {336 return c.text('This is default 404 Not Found', 404)337}338```339340## Error handling341342You can handle errors in your way.343344```js345app.onError = (err, c) => {346 return c.text(`This is error message: ${err.mssage}`, 500)347}348```349357## fire358359`app.fire()` do this.360
4 unmodified lines
365```366367## fetch368362`app.fetch()` is for Cloudflare Module Worker syntax.369`app.fetch` for Cloudflare Module Worker syntax.370371```js372export default {373 fetch(request: Request, env: Env, event: FetchEvent) {
124 unmodified lines