You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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…).
Hello, Everyone.
Who can let me know What is the best way to handle Errors?
Let's discuss everyone's Opinion.
Best
The text was updated successfully, but these errors were encountered: