2
votes

I have a code:

function () {
  return new Promise((resolve, reject) => {
    try {
      fetch(URL, { method: METHOD, body: BODY })
        .then((res) => res.json())
        .then((json) => {
          resolve(json);
        })
        .catch((res) => {
          reject(res);
        })
    } catch (exception) {
      reject(exception);
    }
  });
}

When server responses not with json I've got

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

I know that try-catch do not catch async throws.

I have read

Cannot catch UnhandledPromiseRejectionWarning in promise,

Try Catch unable to catch UnhandledPromiseRejectionWarning,

“UnhandledPromiseRejectionWarning” error even when catch is present

but there is no answer for my question.

2

2 Answers

3
votes

Try catch will not be able to handle error which is thrown asynchronously (i.e, in promise), you must use .catch() for that.

JSfiddle

function someFunc() {
    return new Promise((resolve, reject) => {

        fetch(URL, {method: METHOD, body: BODY})
            .then((res) => res.json())
            .then((json) => {
                resolve(json);
            })
            .catch((err) => {
                reject(err);
            })
    });
}

someFunc()
.then((value)=>{})
.catch((err)=>{console.log(err)})

Edit: When the server responds with no json but with error, your returned promise is rejected. Therefore, you should make sure that you are calling .catch() on your function call (i.e, someFunc().catch(()=>{})). This error comes up if have left your rejected promise unhandled (without catch).

Edit2: Oops. Sorry, misread your question but I guess explanation remains same. If res is not having json() method over it, it will throw the following error when you call res.json()::

Uncaught TypeError: res.json() is not a function

This error will be caught by your .catch() block. Now catch block will return a new rejected promise. When the function is called and if there is no catch() to handle the request, the error which you are talking about will be thrown.

I have explained a bit more here.

0
votes

Try/catch only works for asynchronous actions when wrapping it with an async function.

fetchSomething = async url => {
  try {
     await fetch(url)
  } catch (error) {
     // We will see error here
  }
}

See others ways to catch async error here: https://dev.to/sobiodarlington/better-error-handling-with-async-await-2e5m