undici: Undici.Request and AbortController doesn't work well

Bug Description

Sometimes Aborting Undici.Request causes whole program to stop, even though everything is wrapped around try catch.

Reproducible By

I don’t have minimal reproducible example, as my code is larger in size. But Undici.Fetch doesn’t have this issue.

Here is minimal reproducible example:

const undici = require('undici')

async function testUndici() {
    const controller = new AbortController()
    const {statusCode,headers,trailers,body} = await undici.request("https://github.com/fawazahmed0/tiger/releases/download/v2/pipetocsv.7z", { signal: controller.signal }).catch(console.error)
    setTimeout(()=>controller.abort(), 500)
}
testUndici()

Expected Behavior

Undici.Request and AbortController should work

Logs & Screenshots

node:events:498
      throw er; // Unhandled 'error' event
      ^
DOMException [AbortError]: This operation was aborted
    at new DOMException (node:internal/per_context/domexception:53:5)
    at AbortController.abort (node:internal/abort_controller:395:18)
    at Timeout._onTimeout (T:\xx\other scripts\undici-debug.js:7:31)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7)
Emitted 'error' event on BodyReadable instance at:
    at emitErrorNT (node:internal/streams/destroy:170:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Node.js v22.3.0

Environment

Ubuntu 24.04 & Windows 11 Node v22.3.0 Undici 6.19.1

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 42 (41 by maintainers)

Commits related to this issue

Most upvoted comments

I think the surprising thing here is that this is a hybrid promise / stream API. Both the initial promise for getting the Response object AND the stream are governed by the signal. I suppose that I was only expecting the initial Promise for the headers to be controlled by the signal. I was already controlling the consumption of the body stream using the signal via pipeline(). I expected any possible failure modes to result in promise rejections instead of this subtle interaction with node’s emitter-based legacy.

@mcollina wdyt? I think it’s a reasonable opinion but not sure what to do with it. Would break everyone to change it now.

Hi team, we got bitten by this issue in production like others in this thread.

I think that while Readable and undici are each working as intended, the combination of the two leads to an API that is unnecessarily hostile for a user.

In our case, the issue manifested because we’re holding onto a reference to clientRes to pipe into a subsequent bit of work. However, after obtaining a reference to clientRes and before calling pipeline(clientRes.body, nextConsumer, { signal }), we call signal.throwIfAborted().

This leads to a whole-program crash despite the whole sequence above being orchestrated in an async function, attempting idiomatic use of AbortSignal.

The fix, in our case is the following, which I believe is indicative of the dangerous nature of this interaction:

async function criticalPath() {
  clientRes = await performUndiciRequest(signal);
  
  // This is the fix.
  clientRes.body.on('error', () => {
    // Ignore the error so that we don't get uncaught exceptions and crash.
  });
  
  // ... do some async work
  
  signal.throwIfAborted();
  
  // ... consume the body
  
  await pipeline([clientRes.body, targetStream], { signal });
}

There is nothing to fix. It works as designed.

request returns a body: Stream which gets destroyed with an abort error and emits an error that you are not handling and therefore the process crashes with an unhandled exception. This is normal nodejs behavior. Feel free to open a PR if you think that needs to be explicitly documented by undici.

client.request({
  path: '/',
  method: 'GET',
  signal: abortController.signal
}).then(res=>{
  console.log('Hi! Response received')
  res.body.on('error', error=>{
    console.log('Hi! Error Caught')
    console.error(error) // prints a RequestAbortedError
    client.close()
    server.close()
  })
}).catch(error=>{
  console.log('Hi! Error Caught')
  console.error(error) // should print an RequestAbortedError
  client.close()
  server.close()
})
setTimeout(()=>abortController.abort(),500)