Erros and Handling Http Errors

Erros and Handling Http Errors

So firstly, if you want to generate an error in a javascript app,its very simple:

throw new Error('Something went wrong!');

you can put it into an if( ){ } block to check when you want to generate and where.

if we work with .then() we can use .catch() to catching errors

But when working with async await, we instead use try catch. So we try some code and we catch any potential errors.

The response object, which we get back has this "ok " field, which basically signals whether the response was successful or not. So we can check if response is not ok, like and then generate and throw our own error in that case.

if (!response.ok) {

      }

we can use .status also to throw an error.

if (!response.status) {

      }

Now, when sending HTTP requests, things can also go wrong, of course. You can encounter errors, both technical errors because, for example, you have no network connection, or you do have a network connection and the request is sent but you get back an error response code, something like 404 or 500 or 401 codes.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses

There is a couple of errors in javascript , for example " servers error" which doesn't appear directly on the client screen and we want it to appear , But how can we do that?

if I try to send the request to swapi.dev/api/film instead of films. This is a invalid URL. It's a REST endpoint which is not supported by this REST API and hence, if we save this and we send the request, we don't get back data. It's stuck in the loading state, which of course, is a bad user experience. It would be better to show the user some error so that the user of this applications knows that things went wrong.

images.png

async function fetchMoviesHandler() {
    setIsLoading(true);
    setError(null);
    try {
      const response = await fetch('https://swapi.dev/api/film/');
      // https://developer.mozilla.org/en-US/docs/Web/API/Response
      if (!response.ok) {
        throw new Error('Something went wrong!');
      }


      const data = await response.json();
      const transformedMovies = data.results.map(movieData => (

        {
          id: movieData.episode_id,
          title: movieData.title,
          openingText: movieData.opening_crawl,
          releaseDate: movieData.release_date
        }

      ));
      // console.log(transformedMovies); (6)[{… }, {… }, {… }, {… }, {… }, {… }]

      setMovies(transformedMovies);

    } catch (error) {
      // console.log(error.message); //Something went wrong!
      setError(error.message);
    }
    setIsLoading(false);
  }

Now, if we're not using async await, if we work with then and so on, then we would add catch to catch any errors. Now, when working with async await, we instead use try catch. So we try some code and we catch any potential errors.

Fetch API doesn't treat error status codes as real errors. By default, the Fetch API doesn't do that. Axios, on the other hand, would generate and throw a real error for error status codes. Now, since we're not talking about axios here but the Fetch API, we have to do this on our own and it is easy to do that. I mentioned that the response object, which we get back has this ok field, which basically signals whether the response was successful or not. So we can check if response is not ok, and then generate and throw our own error in that case. So here we can then throw a new Error with some error message of our choice. We could read an error message from the error response we got back from the server or use our own error message, which is what I will do.