Search code examples
reactjsredux-saga

How to receive json return message in saga try catch when it fails?


I have saga try catch for axios request. However, catch(err) returns message just like

Error: Request failed with status code 400

I want to display the error message from the server which is sent by res.state(400).json(errors). On Dev console -> Network, I clearly see my JSON file has returned.

How can I access the returned JSON inside of catch(err) block?


Solution

  • You can catch errors in axios using catch (block or function - depends if you use try/catch or Promise API). You can access the failing response data using error.response.

    Below is an example of useEffect hook fetching the data from an endpoint and handling the error.

    useEffect(() => {
        axios
          .get("https://your-domain/error")
          .then((response) => console.log("Response", response.body))
          .catch((error) =>
            console.log(`HTTP Status Code: ${error.response.status}; data: ${JSON.stringify(error.response.data)}`)
          );
      }, []);
    

    The endpoint itself is simple Express endpoint defined as follows:

    app.get("/error", (req, res) => {
      console.log("error");
      res.status(404).json({ error: "Not found" });
    });
    

    It returns response with 404 status code and {error: "Not found"} body.