这可能看起来很蠢,但我正在尝试在Axios请求失败时获取错误数据。
axios
.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log(error); //Logs a string: Error: Request failed with status code 404
});
是否可以返回一个对象,而不是字符串,包括状态码和内容?例如:
而不是字符串,是否可能获取带有状态码和内容的对象?例如:
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
response
属性,它是如何自动转换为字符串的魔法? - Sebastian Olsenconsole.log
使用toString
方法来格式化Error
对象,与引用response
属性无关。 - Nick Uraltsevconsole.log
在 node.js 的实现中将Error
对象作为一种特殊情况来处理。我无法确定它在浏览器中的具体实现方式,但是如果你在 Chrome DevTools 控制台中调用console.log({ foo: 'bar' });
和console.log(new Error('foo'));
,你会发现结果看起来不同。 - Nick Uraltsev