Skip to content

Commit

Permalink
fix: handle response that is not an instance of Response
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed Dec 28, 2023
1 parent 6fed45b commit e942805
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
11 changes: 11 additions & 0 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const handleResponseError = (e: unknown, outgoing: ServerResponse | Http2ServerR
console.info('The user aborted a request.')
} else {
console.error(e)
outgoing.headersSent
? outgoing.writeHead(500)
: outgoing.writeHead(500, { 'Content-Type': 'text/plain' })
outgoing.end(`Error: ${err.message}`)
outgoing.destroy(err)
}
}
Expand Down Expand Up @@ -54,6 +58,13 @@ const responseViaResponseObject = async (
if (res instanceof Promise) {
res = await res.catch(handleFetchError)
}
if (!(res instanceof Response)) {
return handleResponseError(
// @ts-expect-error the object must have `toString()`
new Error(`The response is not an instance of Response, but ${res.toString()}`),
outgoing
)
}
if (cacheKey in res) {
try {
return responseViaCache(res as Response, outgoing)
Expand Down
15 changes: 13 additions & 2 deletions test/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ describe('Basic', () => {
app.delete('/posts/:id', (c) => {
return c.text(`DELETE ${c.req.param('id')}`)
})
// @ts-expect-error the response is string
app.get('/invalid', () => {
return '<h1>HTML</h1>'
})

const server = createAdaptorServer(app)

Expand Down Expand Up @@ -58,6 +62,14 @@ describe('Basic', () => {
expect(res.status).toBe(200)
expect(res.text).toBe('DELETE 123')
})

it('Should return 500 response - GET /invalid', async () => {
const res = await request(server).get('/invalid')
expect(res.status).toBe(500)
expect(res.headers['content-type']).toBe('text/plain')
// The error message might be changed.
expect(res.text).toBe('Error: The response is not an instance of Response, but <h1>HTML</h1>')
})
})

describe('Routing', () => {
Expand Down Expand Up @@ -478,7 +490,6 @@ describe('Hono compression', () => {
})
})


describe('set child response to c.res', () => {
const app = new Hono()
app.use('*', async (c, next) => {
Expand All @@ -497,4 +508,4 @@ describe('set child response to c.res', () => {
expect(res.status).toBe(200)
expect(res.headers['content-type']).toMatch(/application\/json/)
})
})
})

0 comments on commit e942805

Please sign in to comment.