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
Provenance
- Commit
adb55ca- Tree
91a69d6- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
a66296b
5 files changed+77 added−64 removed
modified:examples/basic/index.js+9 added-8 removed
31 unmodified lines32333435363738394041424336373839404142434445464748495061 unmodified lines31 unmodified lines const ms = Date.now() - start await c.header('X-Response-Time', `${ms}ms`)})
// Handle errorapp.use('*', async (c, next) => { try { await next() } catch (err) { console.error(`${err}`) c.res = c.text('Custom Error Message', 500) }// Custom Not Found Messageapp.notFound((c) => { return c.text('Custom 404 Not Found', 404)})
// Error handlingapp.onError((err, c) => { console.error(`${err}`) return c.text('Custom Error Message', 500)})
// Routingapp.get('/', (c) => c.text('Hono!!'))// Use Response object directlyapp.get('/hello', () => new Response('This is /hello'))61 unmodified linesmodified:src/compose.ts+2 added-1 removed
123445678924 unmodified linesimport { Context } from './context'import type { ErrorHandler } from './hono'
// Based on the code in the MIT licensed `koa-compose` package.export const compose = <T>(middleware: Function[], onError?: Function) => {export const compose = <T>(middleware: Function[], onError?: ErrorHandler) => { return function (context: T, next?: Function) { let index = -1 return dispatch(0) async function dispatch(i: number): Promise<T> {24 unmodified linesmodified:src/hono.test.ts+8 added-14 removed
14 unmodified lines15 c.status(201)16 return c.html('<h1>Hono!!!</h1>')17 })18 19- app.notFound = () => {20- return new Response('not found', {21- status: 404,22- })23- }24-19 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 lines259 expect(res.headers.get('x-message-2')).toBe('custom-header-2')260 })261 })262 269-describe('404 Not Found', () => {263+describe('Not Found', () => {264 const app = new Hono()265 272- app.notFound = (c) => {266+ app.notFound((c) => {267 return c.text('Custom 404 Not Found', 404)274- }268+ })269 270 app.get('/hello', (c) => {271 return c.text('hello')272 })40 unmodified lines313 app.use('/error-middleware', async () => {314 throw new Error('This is Middleware Error')315 })316 323- 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+ })321 322 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')328 329 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 })336 337 describe('Request methods with custom middleware', () => {39 unmodified linesmodified:src/hono.ts+26 added-16 removed
19 unmodified lines20 c: Context<RequestParamKeyType>,21 next?: Function22 ) => Response | Promise<Response>23 export type MiddlewareHandler = (c: Context, next: Function) => Promise<void>24+export type NotFoundHandler = (c: Context) => Response25+export type ErrorHandler = (err: Error, c: Context) => Response26 27 // eslint-disable-next-line @typescript-eslint/no-unused-vars28 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`29 ? Name21 unmodified lines51 this.middlewareRouters = []52 this.tempPath = null53 }54 55+ notFoundHandler: NotFoundHandler = (c: Context) => {56+ const message = '404 Not Found'57+ return c.text(message, 404)58+ }59+60+ errorHandler: ErrorHandler = (err: Error, c: Context) => {61+ console.error(`${err.message}`)62+ const message = 'Internal Server Error'63+ return c.text(message, 500)64+ }65+66 /* 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 lines120 router.add(METHOD_NAME_OF_ALL, path, middleware)121 this.middlewareRouters.push(router)122 }123 124+ onError(handler: ErrorHandler): Hono {125+ this.errorHandler = handler126+ return this127+ }128+129+ notFound(handler: NotFoundHandler): Hono {130+ this.notFoundHandler = handler131+ return this132+ }133+134 // addRoute('get', '/', handler)135 addRoute(method: string, path: string, handler: Handler): Hono {136 method = method.toUpperCase()137 if (this.tempPath) {26 unmodified lines164 const url = new URL(c.req.url)165 return url.searchParams.get(key)166 }167 145- const handler = result ? result.handler : this.notFound168+ const handler = result ? result.handler : this.notFoundHandler169 170 const middleware = []171 172 for (const mr of this.middlewareRouters) {13 unmodified lines186 }187 188 middleware.push(wrappedHandler)189 167- 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)193 194 const context = await composed(c)195 196 return context.res11 unmodified lines208 addEventListener('fetch', (event: FetchEvent): void => {209 event.respondWith(this.handleEvent(event))210 })211 }189-190- // 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- }196-197- // 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 lines70 - 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)78 79 ## Routing47 unmodified lines127 ```128 129 ### no strict130 129-If `strict` is set `false`, `/hello`and`/hello/` are treated the same. Default is `true`.131+If `strict` is set false, `/hello`and`/hello/` are treated the same.132 133 ```js132-const app = new Hono({ strict: false })134+const app = new Hono({ strict: false }) // Default is true135 136 app.get('/hello', (c) => c.text('/hello or /hello/'))137 ```138 50 unmodified lines189 190 app.get('/message/hello', (c) => c.text('Hello Middleware!'))191 ```192 193+## Error194+195+### Not Found196+197+`app.notFound` for customizing Not Found Response.198+199+```js200+app.notFound((c) => {201+ return c.text('Custom 404 Message', 404)202+})203+```204+205+### Error Handling206+207+`app.onError` handle the error and return the customized Response.208+209+```js210+app.onError((err, c) => {211+ console.error(`${err}`)212+ return c.text('Custom Error Message', 500)213+})214+```215+216 ## Context217 218 To handle Request and Reponse, you can use Context object.219 28 unmodified lines248 ### Shortcuts for Response249 250 ```js251 app.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)230-257+ // Return the response body258 return c.body('Thank you for comming')259 })260 ```261 42 unmodified lines304 ```305 306 ### c.notFound()307 281-Return the default `404 Not Found` Response.308+Return the `404 Not Found` Response.309 310 ```js311 app.get('/notfound', (c) => {312 return c.notFound()40 unmodified lines353 ...354 })355 ```356 330-## Not Found331-332-You can write the default `404 Not Found` Response.333-334-```js335-app.notFound = (c) => {336- return c.text('This is default 404 Not Found', 404)337-}338-```339-340-## Error handling341-342-You can handle errors in your way.343-344-```js345-app.onError = (err, c) => {346- return c.text(`This is error message: ${err.mssage}`, 500)347-}348-```349-357 ## fire358 359 `app.fire()` do this.360 4 unmodified lines365 ```366 367 ## fetch368 362-`app.fetch()` is for Cloudflare Module Worker syntax.369+`app.fetch` for Cloudflare Module Worker syntax.370 371 ```js372 export default {373 fetch(request: Request, env: Env, event: FetchEvent) {124 unmodified lines