1

How to purposely make a promise fail? Sometime I just skip the test and assume everything is fine, but I want to purposely make the promise to fail so that my catch is working.

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()
}
Hoknimo
  • 533
  • 2
  • 6
  • 15

2 Answers2

1

You can throw new Error('<your string here>');:

Note that catch is not something to be used with function syntax - the proper syntax is 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();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Why `throw('something is wrong')` also worked? i tried without the `new`, just `throw Error('something is wrong')` worked too. – Hoknimo May 19 '18 at 06:24
  • 1
    See [this answer](https://stackoverflow.com/questions/9156176/what-is-the-difference-between-throw-new-error-and-throw-someobject#answer-13016600) and the one below it - `throw new Error` is said to be more reliable, though it probably doesn't matter as much nowadays because more browsers are standards-compliant. – CertainPerformance May 19 '18 at 06:28
0

use the throw statement, maybe?

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

user-defined exception-types (alike one commonly has them in Java or PHP) are also possible and recommended, because one barely can differ the type by a string and otherwise can easily check the typeof the exception in the catch block. just learned from the MDN, that one eg. can also throw DOMException and Error.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216