TOLULOPE ADETULA
TOLULOPE ADETULA

Reputation: 788

catch block isn't getting my errors from the fetch api

I have a code that is exactly the same as the image. The fetch method is wrapped ina catch block, both it just doesn't, catch the error. From my node backend, I've tried different methods of rendering the error so it can be caught on the frontend.

React Code to handle error

const  errorHandler = (err, req, res, next) => {
    if (typeof (err) === "string") {
        // custom application error
        return res.status(400).json({ message: err });
    }

    if (err.name === "UnauthorizedError") {
        // jwt authentication error
        return res.status(401).json({ message: "Invalid Token" });
    }
    if (err.name === "JsonWebTokenError") {
        // jwt authentication error
        return res.status(401).json({ message: "Invalid Token" });
    }

    // default to 500 server error
    return res.status(501).render("error" , { message: err.message });

};

This is my node backend

Upvotes: 0

Views: 469

Answers (1)

Ado
Ado

Reputation: 817

You can check errors with this simple function

handleFetchErrors (response) {
    if (!response.ok) throw Error(response.statusText)
    return response
}

Upvotes: 2

Related Questions