使用Axios处理错误时遇`error.toJSON() is not a function`报错如何解决?
解决
error.toJSON is not a function报错的优化方案 你运行代码时遇到error.toJSON is not a function报错,原代码如下:
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"); } };
报错原因
不是所有捕获到的错误对象都自带toJSON()方法:Axios封装的请求错误(AxiosError)会提供这个方法来格式化错误,但如果出现非Axios层面的异常(比如网络完全中断、参数类型错误导致的同步报错),捕获到的可能是原生Error甚至普通对象,这类对象没有toJSON()方法,直接调用就会触发报错。
优化方案
1. 先判断方法存在性再调用
最直接的修复是先检查error是否有toJSON方法,再决定是否调用:
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) { // 兼容无toJSON方法的错误对象 const errorDetails = typeof error.toJSON === 'function' ? error.toJSON() : error; console.error(error.response?.data, errorDetails); throw new Error("安装依赖失败"); } };
2. 分层收集错误信息
针对Axios错误的不同场景,分层收集更全面的错误细节,避免依赖单一方法:
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) { let errorInfo = {}; // 区分Axios错误的不同状态 if (error.response) { // 请求已发送并收到非2xx响应 errorInfo = { status: error.response.status, data: error.response.data, headers: error.response.headers }; } else if (error.request) { // 请求已发送但未收到响应 errorInfo = { request: error.request }; } else { // 请求初始化或同步代码报错 errorInfo = { message: error.message, stack: error.stack }; } // 若存在toJSON方法,补充结构化信息 if (typeof error.toJSON === 'function') { errorInfo = {...errorInfo, ...error.toJSON()}; } console.error('安装依赖失败:', errorInfo); throw new Error("安装依赖失败"); } };
3. 自定义错误类(可选)
如果需要统一错误格式,方便上层调用者处理,可以自定义错误类:
class DependencyInstallError extends Error { constructor(message, details) { super(message); this.name = 'DependencyInstallError'; this.details = details; } } 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) { const errorDetails = typeof error.toJSON === 'function' ? error.toJSON() : { message: error.message, stack: error.stack }; console.error(error.response?.data, errorDetails); throw new DependencyInstallError("安装依赖失败", errorDetails); } };
核心思路
处理异步请求错误时,不要默认所有错误都是Axios封装的对象,必须做方法存在性判断,同时根据错误场景分层收集信息,保证日志清晰且错误抛出后能提供足够上下文给上层逻辑。
内容的提问来源于stack exchange,提问作者Didi
相关产品推荐
相关产品推荐

