Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: catch ERR_INVALID_URL error in listener #162

Merged
merged 1 commit into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading