지금까지 api 통신을 할 때 error는 그냥 console.log(error) 이렇게 확인했다.
const handleRequest = async request => {
try {
const response = await request();
return response.data;
} catch (err) {
console.log(JSON.stringify(err, null, 2));
throw err; // Rethrow the error to handle at react query
}
};
이런 식으로 했었다. 그러면 에러 로그는 아래와 같이 보였다.
"message": "Request failed with status code 401",
"name": "AxiosError",
"stack": "생략",
"config": {
생략
},
"adapter": [
"xhr",
"http",
"fetch"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": "Bearer 생략"
},
"method": "get",
"url": "생략"
},
"code": "ERR_BAD_REQUEST",
"status": 401
}
에러에 대한 정보가 거의 없어서 항상 의문만 품고 답답해 했는데 axios에서 에러 핸들링 부분을 보니까 다르게 하더라.
https://axios-http.com/kr/docs/handling_errors
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// 요청이 전송되었고, 서버는 2xx 외의 상태 코드로 응답했습니다.
console.log(error.response.data);
...
이렇게 error.response로 보는 것이다.
세상에 나도 error.response로 찍어보니
{
"data": {
"error": "At least one of content, category_id, start_date, end_date, is_completed must be provided"
},
"status": 400,
"headers": {
"allow": "GET, POST, PATCH, DELETE, HEAD, OPTIONS",
"content-length": "101",
"content-type": "application/json",
"cross-origin-opener-policy": "same-origin",
... 이하 생략
}
error만 로그 찍어보면 response 속성은 없었는데 왜 error.response를 찍으면 더 자세한 정보가 나오지...!
찾아보니까
https://github.com/axios/axios/issues/960

The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.
string representation가 뭐지 콘솔 로그가 객체 구조를 출력하는게 아니라 string representation를 출력해서 에러 객체가 가진 모든 속성을 안보여주는 것이었나
GPT에게도 물어보았다.
해결방법으로 JSON.stringify(error, null, 2), console.dir(error, { depth: null })가 있다는데 난 애초에 JSON.stringfy로 로그를 찍고 있었다.

JSON.stringify(error, null, 2)로 Axios 에러 객체를 문자열로 변환할 때 response 속성이 보이지 않는 이유는, 자바스크립트에서 Error 객체의 속성들이 enumerable하지 않기 때문입니다. enumerable 속성은 객체의 속성이 for...in 루프나 Object.keys 메서드에서 열거될 수 있는지를 나타냅니다. Error 객체의 경우, message, name 등의 속성은 기본적으로 enumerable하지 않으며, 이는 JSON.stringify가 해당 속성들을 직렬화하지 않도록 합니다.
또이잉
console.log는 enumerable 속성만 출력한다..?
Error 객체의 경우, message, name 등의 속성은 기본적으로 enumerable하지 않으며 이 부분에서 또 이상한건 message, name 등은 잘 나왔는데
흐으음 신기한 세계다 앞으로 더 찾아볼 것
1. 콘솔 로그가 객체 구조를 출력하는게 아니라 string representation를 출력한다?
2. 콘솔 로그는 enumerable 속성만 출력한다?