Search code examples
javascriptnode.jstry-catchytdlunhandled-promise-rejection

Cannot handle Unhandled Promise Rejection using try-catch


Hi I just downloaded ytdl-core module and I am encountering a Promise Rejection which I cannot handle! Can anyone please help?

app.get("/getaudio", async (req, res) => {
  const videoID = req.query.v;
  const quality = req.query.q;
  try {
    ytdl("http://www.youtube.com/watch?v=" + videoID, {
      quality: quality,
      filter: "audioonly",
    }).pipe(res);
  } catch (e) {
    res.status(500).send("Encountered Error: " + e.message);
  }
});

Here is the code I wrapped the whole thing in a try catch block but still cannot handle the Promise Rejection Any pointers is Appreciated.

Here is the stacktrace if this helps:

(node:1752) UnhandledPromiseRejectionWarning: Error: No such format found: asdasd
    at Object.exports.chooseFormat (D:\Code and Other Things\YTAudioStream\node_modules\ytdl-core\lib\format-utils.js:168:11)
    at downloadFromInfoCallback (D:\Code and Other Things\YTAudioStream\node_modules\ytdl-core\lib\index.js:86:26)
    at D:\Code and Other Things\YTAudioStream\node_modules\ytdl-core\lib\index.js:20:5
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

I know I provided an invalid quality param and that is intentional, I want to handle this rejection in my code


Solution

  • ytdl returns a readable stream and handling stream errors are a little tricky. You need to use .on() to detect errors, So:

    ytdl("http://www.youtube.com/watch?v=" + videoID, {
      quality: quality,
      filter: "audioonly",
    }).on('error', (err) => console.log(err)).pipe(res);
    

    But if you really want to use try-catch then I suppose you can throw it yourself:

    ytdl("http://www.youtube.com/watch?v=" + videoID, {
      quality: quality,
      filter: "audioonly",
    }).on('error', (err) => throw err).pipe(res);