Skip to content

Commit

Permalink
fix: catch ERR_INVALID_URL error in listener (#162)
Browse files Browse the repository at this point in the history
  • Loading branch information
usualoma authored Apr 19, 2024
1 parent c22f750 commit d847e60
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
22 changes: 11 additions & 11 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,18 +159,18 @@ export const getRequestListener = (
) => {
let res

// `fetchCallback()` requests a Request object, but global.Request is expensive to generate,
// so generate a pseudo Request object with only the minimum required information.
const req = newRequest(incoming)

// Detect if request was aborted.
outgoing.on('close', () => {
if (incoming.destroyed) {
req[getAbortController]().abort()
}
})

try {
// `fetchCallback()` requests a Request object, but global.Request is expensive to generate,
// so generate a pseudo Request object with only the minimum required information.
const req = newRequest(incoming)

// Detect if request was aborted.
outgoing.on('close', () => {
if (incoming.destroyed) {
req[getAbortController]().abort()
}
})

res = fetchCallback(req, { incoming, outgoing } as HttpBindings) as
| Response
| Promise<Response>
Expand Down
22 changes: 22 additions & 0 deletions test/listener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ import { getRequestListener } from '../src/listener'
import { GlobalRequest, Request as LightweightRequest } from '../src/request'
import { GlobalResponse, Response as LightweightResponse } from '../src/response'

describe('Invalid request', () => {
const requestListener = getRequestListener(jest.fn())
const server = createServer(async (req, res) => {
await requestListener(req, res)

if (!res.writableEnded) {
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.end('error handler did not return a response')
}
})

it('Should return server error for a request w/o host header', async () => {
const res = await request(server).get('/').set('Host', '').send()
expect(res.status).toBe(500)
})

it('Should return server error for a request invalid host header', async () => {
const res = await request(server).get('/').set('Host', 'a b').send()
expect(res.status).toBe(500)
})
})

describe('Error handling - sync fetchCallback', () => {
const fetchCallback = jest.fn(() => {
throw new Error('thrown error')
Expand Down

0 comments on commit d847e60

Please sign in to comment.