【问题标题】:purposely throw error in a promise?故意在承诺中抛出错误?
【发布时间】:2018-10-29 12:09:05
【问题描述】:

如何故意让承诺失败?有时我只是跳过测试并假设一切都很好,但我想故意做出失败的承诺,以便我的捕获起作用。

exports.submitJob = async (req, res, next) => {
    const { cv } = req.body
    const userId = req.user._id

    try {

      if(!cv) {
        //how to pass error to catch block?
      }
      const save_submission = new Submission({
        userId,
        cv
      }).save()


    } catch(e => {
      res.json({
        status: 0,
        error: e
      })
    })

    next()
}

【问题讨论】:

  • 您是否尝试抛出错误?

标签: javascript ecmascript-6


【解决方案1】:

您可以throw new Error('<your string here>');:

请注意,catch 不能与 function 语法一起使用 - 正确的语法是 catch (e) { /* block that uses e */ }

const submitJobWhichWillFail = async (req, res, next) => {
  const cv = null;
  try {
    if (!cv) {
      throw new Error('cv must not be falsey!');
    }
    const save_submission = new Submission({
      userId,
      cv
    }).save()


  } catch (e) {
    console.log('res.json with error ' + e);
  }
}
submitJobWhichWillFail();

【讨论】:

  • 为什么throw('something is wrong') 也有效?我试过没有new,只是throw Error('something is wrong')也工作了。
  • 参见this answer 和它下面的throw new Error 据说更可靠,尽管现在它可能不那么重要了,因为更多的浏览器都符合标准。
【解决方案2】:

使用throw 语句,也许?

if(!cv) {throw("cv is absent");}

用户定义的异常类型(类似于 Java 或 PHP 中的常见异常类型)也是可能的并且推荐使用,因为几乎不能通过字符串来区分类型,否则可以轻松检查 typeof 中的异常987654326@ 块。刚刚从 MDN 中学到了,例如。也可以抛出DOMException和Error。

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多