JavaScript Handling Errors

George Roberts
George Roberts
Full Stack JavaScript Techdegree Student 8,474 Points

Why is a throw statement not required when new Error('...') is passed to Promise.reject()?

Hi, I'm just curious why, when new Error('...') is passed to Promise.reject() below, it doesn't need to be preceded by the throw statement? Thanks

function checkStatus(response) {
  if (response.ok) {
    // console.log(Promise.resolve(response));
    return Promise.resolve(response);
  } else {
    return Promise.reject(new Error(response.statusText)); 
  }
}

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,941 Points

From MDN the syntax is:

Promise.reject(reason); and returns a promise.

Description

The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error.

From MDN on error

The Error object can also be used as a base object for user-defined exceptions

So errors don't have to be thrown to be useful. I would think in this case if you could throw the error you would no longer be returning a promise

This stack overflow may also be of interest as it discusses reject Vs. throw.

George Roberts
George Roberts
Full Stack JavaScript Techdegree Student 8,474 Points

Thanks, your last sentence made it clear to me. Also found this within the stack overflow article which helped solidify it for me: "TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise".