Skip to content
Myr

Handle 404

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

authored by Yusuke Wada · committed by Yusuke Wada · parent 8c96d99 · Browse files · 3 files+48 added−7 removed
This commit

State

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

Diff stats

3 files+48 added−7 removed

  • tests:+29 added−0 removed
  • other:+19 added−7 removed

3 files+48 added−7 removed

modified:src/hono.js+2 added-3 removed
modified:src/hono.test.js+29 added
111 unmodified lines
112 expect(await res.headers.get('x-custom')).toBe('root')113 expect(await res.headers.get('x-message-2')).toBe('custom-header-2')114 })115})116117describe('Custom 404', () => {118 const app = new Hono()119120 const customNotFound = async (c, next) => {121 next()122 if (c.res.status === 404) {123 c.res = new fetch.Response('Custom 404 Not Found', { status: 404 })124 }125 }126127 app.notFound = () => {128 return new fetch.Response('Default 404 Nout Found', { status: 404 })129 }130131 app.use('*', customNotFound)132 app.get('/hello', () => {133 return new fetch.Response('hello')134 })135 it('Custom 404 Not Found', async () => {136 let req = new fetch.Request('https://example.com/hello')137 let res = await app.dispatch(req)138 expect(res.status).toBe(200)139 req = new fetch.Request('https://example.com/foo')140 res = await app.dispatch(req)141 expect(res.status).toBe(404)142 expect(await res.text()).toBe('Custom 404 Not Found')143 })144})
modified:README.md+17 added-4 removed
114 unmodified lines
115116### Custom Middleware117118```js119const logger = (c, next) => {119const logger = async (c, next) => {120 console.log(`[${c.req.method}] ${c.req.url}`)121 next()122}123124const addHeader = (c, next) => {124const addHeader = async (c, next) => {125 next()126 c.res.headers.add('x-message', 'This is middleware!')127}128
2 unmodified lines
131132app.get('/message/hello', () => 'Hello Middleware!')133```134135### Custom 404 Response136137```js138const customNotFound = async (c, next) => {139 next()140 if (c.res.status === 404) {141 c.res = new Response('Custom 404 Not Found', { status: 404 })142 }143}144145app.use('*', customNotFound)146```147148## Context149150### req151
6 unmodified lines
158159### res160161```js149app.use('/', (c, next) => {162app.use('/', async (c, next) => {163 next()151 c.res.headers.append('X-Debug', 'Debug message')164 await c.res.headers.append('X-Debug', 'Debug message')165})166```167168## Request
35 unmodified lines