In JavaScript, when using a fetch() call that results in an exception (e.g., a network error), only the catch() block is executed, not the then() block. Here's how it works in detail:
- If the fetch() request succeeds in making the HTTP request (even if the response is an error, such as a 404 or 500 status code), it does not reject the promise. The then() block is called, and you need to check the response.ok property or response.status to determine if the response was successful.
- If the fetch() call fails completely due to a network error, DNS failure, or other reasons that prevent it from connecting to the server, the promise is rejected, and the catch() block is executed.
fetch('https://example.com/api/data')
.then(response => {