简体   繁体   中英

Getting the error message `error.toJSON() is not a function` while handling errors in axios

When I run my code, i get the message error.toJSON is not a function . How am I supposed to handle this error better?


const installDependencies = async (BASE_URL, body) => {
  try {
    const headers = {
      "Content-type": "application/json",
    };
    const response = await axios.post(`${BASE_URL}/data`, body, { headers });
    return response;
  } catch (error) {
    console.error(error.response?.data, error.toJSON());
    throw new Error("Failed to install dependencies");
  }
};

It's possible for your catch to handle either an AxiosError or any other throwable.

Axios provides a utility function to determine if it's the former

const installDependencies = async (baseURL, body) => {
  try {
    return await axios.post("/data", body, { baseURL });
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.error(error.response?.data, error.toJSON());
    } else {
      console.error(error);
    }

    throw new Error("Failed to install dependencies");
  }
};

See https://github.com/axios/axios/#typescript


FYI your headers were redundant and Axios provides a simpler option for setting a baseURL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM