SWS-5007 / My-Experience

13 stars 0 forks source link

Fetch API - What is the best way to handle Errors ? #37

Open SWS-5007 opened 8 months ago

SWS-5007 commented 8 months ago

Hello, Everyone. Who can let me know What is the best way to handle Errors? Let's discuss everyone's Opinion. Best

SWS-5007 commented 8 months ago

Here is my Opinion.

Common way to handle erros inside the try block is throwing an error when response.ok isn’t true in order to make the catch block be executed, so that we can handle all errors at the same place. See example bellow for a better understanding:

try {
  const response = await fetch('https://restcountries.com/v4.1/all');

  if (response.ok) {
    console.log('Promise resolved and HTTP status is successful');
    // ...do something with the response
  } else {
    // Custom message for failed HTTP codes
    if (response.status === 404) throw new Error('404, Not found');
    if (response.status === 500) throw new Error('500, internal server error');
    // For any other server error
    throw new Error(response.status);
  }
} catch (error) {
  console.error('Fetch', error);
  // Output e.g.: "Fetch Error: 404, Not found"
}

Here we throw errors to handle them in the catch block and also display a custom message in the console depending on the type of error.

I hope this will be helpful for you too. Best