最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handling Js promise rejection - Stack Overflow

programmeradmin2浏览0评论

How do you handle an error (eg. "new error" below) that is outside of the promise?

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

testError().catch(err => {
        return err;  // code doesn't come here
    })
    .then(ok => {
        console.log(ok)
    });

How do you handle an error (eg. "new error" below) that is outside of the promise?

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

testError().catch(err => {
        return err;  // code doesn't come here
    })
    .then(ok => {
        console.log(ok)
    });
Share Improve this question edited Dec 29, 2021 at 1:16 Mr. ProxY 171 silver badge4 bronze badges asked Apr 14, 2017 at 7:15 StanleyStanley 2,8166 gold badges27 silver badges45 bronze badges 3
  • 1 Use try/catch – Trash Can Commented Apr 14, 2017 at 7:19
  • 1 You'll have to throw the error inside the promise function for the .catch() to work. – Shilly Commented Apr 14, 2017 at 7:19
  • See How can I catch an asynchronous error using JS promises? – guest271314 Commented Apr 14, 2017 at 7:25
Add a comment  | 

5 Answers 5

Reset to default 6

If you're not sure whether a function will throw (or return a value) synchronously, you can call it using .then(). This will wrap it so that the result will be handled consistently no matter how it is produced:

function testError() {
  throw new Error("new error") // how to handle this?
  var p123 = new Promise(function(resolve, reject) {
    resolve(123)
  });
  return p123
};

Promise.resolve()
  .then(testError)
  .catch(err => {
    console.error(err);
    return err; 
  })
  .then(ok => {
    console.log(ok.message)
  });

Since the error doesn't involve the async code, a regular try-catch should do fine here:

try {
  testError().catch(err => {
    return err;  // code doesn't come here
  })
  .then(ok => {
     console.log(ok)
  });
}
catch(e) {
   // 
}

Note that when the async-await pattern finally becomes the native way of resolving promises, the try-catch will also become the native way of handling errors:

try {
    var ok = await testError();
    console.log(ok)
}
catch(e) {
    console.log('e:' +e);
}

As one can easily verify, this one correctly handles both the sync and the async error and is much cleaner than then-catch.

If you can, rewrite your testError function like so

function testError () {
  return new Promise(function (resolve, reject) {
     throw new Error('new error')
     resolve(123)
  })
}

testError().then(ok => console.log(ok),
                 err => console.error(err.message))

  1. Run it once to see it throw the error in console.error
  2. Comment out the throw line to see the promise resolve successfully

Since the error is thrown outside of the promises, you cannot catch it using a promise catch statement.

You can use a try/catch to catch the error instead.

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

try {
  testError().then(ok => {
    console.log(ok)
  });
} catch (err) {
  console.log(err.message);
}

You rewrite it, because making a caller check for both exceptions and rejections is an anti-pattern:

function testError() {
  return Promise.resolve().then(() => {
    throw new Error("new error"); // rejects returned promise
    return new Promise(function(resolve) {
      resolve(123);
    });
  });
}

testError().catch(err => console.log("Caught " + err));

This is implicit with async functions; they always return a promise:

async function testError() {
  throw new Error("new error"); // rejects implicit promise
  return await new Promise(function(resolve) {
    resolve(123);
  });
}

testError().catch(err => console.log("Caught " + err));

发布评论

评论列表(0)

  1. 暂无评论