无法使用 try-catch 处理未处理的承诺拒绝

问题描述

嗨,我刚刚下载了 ytdl-core 模块,但遇到了无法处理的 Promise Rejection!任何人都可以帮忙吗?

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);
  }
});

这是代码 我将整个事情包裹在 try catch 块中,但仍然无法处理 Promise Rejection 感谢任何指点。

如果有帮助,这里是堆栈跟踪:

(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)

我知道我提供了一个无效的质量参数,这是故意的,我想在我的代码中处理这个拒绝

解决方法

ytdl 返回可读流,处理流错误有点棘手。您需要使用 .on() 来检测错误,所以:

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

但是如果你真的想使用 try-catch 那么我想你可以自己抛出它:

ytdl("http://www.youtube.com/watch?v=" + videoID,(err) => throw err).pipe(res);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...