Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
SWS-5007 opened this issue Jan 10, 2024 · 1 comment
Open

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

SWS-5007 opened this issue Jan 10, 2024 · 1 comment

Comments

@SWS-5007
Copy link
Owner

SWS-5007 commented Jan 10, 2024

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

@SWS-5007
Copy link
Owner Author

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.

  • when response.ok returns false, we can simple throw an error, so the catch block will be executed
  • catch will then handle all types of errors
  • catch accepts an argument that can be customized when throwing errors from the try block
  • response.status can be used to check the returned HTTP status code to display customized messages in the console (like 400, 404, 500…).

I hope this will be helpful for you too.
Best

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant