Skip to content
Myr

fix: fixed the issue logger called twice (#494)

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

* fix: fixed the issue logger called twice * add handling the error and shorten code

authored by Yusuke Wada · committed by GitHub · parent 9793e6b · Browse files · 9 files+74 added−30 removed
This commit

State

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

Diff stats

9 files+74 added−30 removed

  • tests:+36 added−0 removed
  • other:+38 added−30 removed

9 files+74 added−30 removed

modified:deno_dist/deno/serve-static.ts+1 added-1 removed
modified:deno_dist/middleware/serve-static/serve-static.ts+1 added-1 removed
modified:deno_dist/context.ts+2 added-1 removed
1import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono.ts'2import { defaultNotFoundMessage } from './hono.ts'3import type { CookieOptions } from './utils/cookie.ts'4import { serialize } from './utils/cookie.ts'5import type { StatusCode } from './utils/http-status.ts'6import { isAbsoluteURL } from './utils/url.ts'
84 unmodified lines
91 }92 }9394 get res(): Response {94 return (this._res ||= new Response())95 return (this._res ||= new Response(defaultNotFoundMessage, { status: 404 }))96 }9798 set res(_res: Response) {99 this._res = _res
93 unmodified lines
modified:deno_dist/hono.ts+15 added-12 removed
33 unmodified lines
34) => Response3536export type Next = () => Promise<void>3738export const defaultNotFoundMessage = '404 Not Found'3940// eslint-disable-next-line @typescript-eslint/no-unused-vars41type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`42 ? Name43 : NameWithPattern
80 unmodified lines
124 Object.assign(this, init)125 }126127 private notFoundHandler: NotFoundHandler = (c: Context) => {126 const message = '404 Not Found'128 const message = defaultNotFoundMessage129 return c.text(message, 404)130 }131132 private errorHandler: ErrorHandler = (err: Error, c: Context) => {
73 unmodified lines
206 // Do not `compose` if it has only one handler207 if (result && result.handlers.length === 1) {208 const handler = result.handlers[0]209 try {208 const response = handler(c, async () => {})209 if (response) {210 if (response instanceof Promise) {211 const awaited = await response212 if (awaited) return awaited213 } else {214 return response215 }210 const res = handler(c, async () => {})211 if (res) {212 const awaited = res instanceof Promise ? await res : res213 if (awaited) return awaited214 }217 // Do nothing218 } catch {}215 return this.notFoundHandler(c as Context)216 } catch (err) {217 if (err instanceof Error) {218 return this.errorHandler(err, c as Context)219 }220 throw err221 }222 }223224 const handlers = result ? result.handlers : [this.notFoundHandler]225
7 unmodified lines
233 )234 }235 } catch (err) {236 if (err instanceof Error) {234 return this.errorHandler(err, c as Context<string, Environment>)237 return this.errorHandler(err, c as Context)238 }239 throw err240 }241
16 unmodified lines
modified:src/deno/serve-static.ts+1 added-1 removed
modified:src/middleware/serve-static/serve-static.ts+1 added-1 removed
modified:src/context.ts+2 added-1 removed
1import type { Environment, NotFoundHandler, ContextVariableMap, Bindings } from './hono'2import { defaultNotFoundMessage } from './hono'3import type { CookieOptions } from './utils/cookie'4import { serialize } from './utils/cookie'5import type { StatusCode } from './utils/http-status'6import { isAbsoluteURL } from './utils/url'
84 unmodified lines
91 }92 }9394 get res(): Response {94 return (this._res ||= new Response())95 return (this._res ||= new Response(defaultNotFoundMessage, { status: 404 }))96 }9798 set res(_res: Response) {99 this._res = _res
93 unmodified lines
modified:src/hono.test.ts+36 added
1import type { Context } from './context'2import type { Next } from './hono'3import { Hono } from './hono'4import { logger } from './middleware/logger'5import { poweredBy } from './middleware/powered-by'67describe('GET Request', () => {8 const app = new Hono()
1048 unmodified lines
1057 expect(await res.text()).toBe('Bar')1058 expect(res.headers.get('content-type')).toBe('text/plain; charset=UTF-8')1059 })1060})10611062describe('Count of logger called', () => {1063 // It will be added `2` each time the logger is called once.1064 let count = 01065 let log = ''10661067 const app = new Hono()10681069 const logFn = (str: string) => {1070 count++1071 log = str1072 }10731074 app.use('*', logger(logFn))1075 app.get('/', (c) => c.text('foo'))10761077 it('Should be called two times', async () => {1078 const res = await app.request('http://localhost/not-found')1079 expect(res).not.toBeNull()1080 expect(res.status).toBe(404)1081 expect(await res.text()).toBe('404 Not Found')1082 expect(count).toBe(2)1083 expect(log).toMatch(/404/)1084 })10851086 it('Should be called two times / Custom Not Found', async () => {1087 app.notFound((c) => c.text('Custom Not Found', 404))1088 const res = await app.request('http://localhost/custom-not-found')1089 expect(res).not.toBeNull()1090 expect(res.status).toBe(404)1091 expect(await res.text()).toBe('Custom Not Found')1092 expect(count).toBe(4)1093 expect(log).toMatch(/404/)1094 })1095})
modified:src/hono.ts+15 added-12 removed
33 unmodified lines
34) => Response3536export type Next = () => Promise<void>3738export const defaultNotFoundMessage = '404 Not Found'3940// eslint-disable-next-line @typescript-eslint/no-unused-vars41type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`42 ? Name43 : NameWithPattern
80 unmodified lines
124 Object.assign(this, init)125 }126127 private notFoundHandler: NotFoundHandler = (c: Context) => {126 const message = '404 Not Found'128 const message = defaultNotFoundMessage129 return c.text(message, 404)130 }131132 private errorHandler: ErrorHandler = (err: Error, c: Context) => {
73 unmodified lines
206 // Do not `compose` if it has only one handler207 if (result && result.handlers.length === 1) {208 const handler = result.handlers[0]209 try {208 const response = handler(c, async () => {})209 if (response) {210 if (response instanceof Promise) {211 const awaited = await response212 if (awaited) return awaited213 } else {214 return response215 }210 const res = handler(c, async () => {})211 if (res) {212 const awaited = res instanceof Promise ? await res : res213 if (awaited) return awaited214 }217 // Do nothing218 } catch {}215 return this.notFoundHandler(c as Context)216 } catch (err) {217 if (err instanceof Error) {218 return this.errorHandler(err, c as Context)219 }220 throw err221 }222 }223224 const handlers = result ? result.handlers : [this.notFoundHandler]225
7 unmodified lines
233 )234 }235 } catch (err) {236 if (err instanceof Error) {234 return this.errorHandler(err, c as Context<string, Environment>)237 return this.errorHandler(err, c as Context)238 }239 throw err240 }241
16 unmodified lines