JSON.stringify(error) = {} ??

긴가민가·2022년 12월 28일
0

문제 사항 해결기

목록 보기
3/7
post-thumbnail

원인

Error 발생 시, 필자는 로그를 파일로 남기기 위해 JSON.stringify를 사용합니다.

try {
  // blabla..
  throw new Error('error test');
} catch (error) {
  console.log(JSON.stringify(error)); // {} ??
}

이 때 에러의 로그는 {}입니다..?

이유가 뭘까?

JSON.stringify의 파라미터로 객체(object)를 전달한다면, 열거 가능한 속성(enumerable property)만 처리합니다.

const error = new Error('test error');

console.log(Object.getOwnPropertyDescriptors(error)); // property 설명 보기

Error 객체의 모든 property의 enumerable 값이 false이기 때문에, JSON.stringify(error){}으로 처리되는 것이었다..!

해결

JSON.stringify의 두번째 파라미터에 열거할 명칭을 임의로 넣어주면 됩니다.

JSON.stringify(error, Object.getOwnPropertyNames(error));

// '{"stack":"Error: test error\\\\n    at <anonymous>:1:15","message":"test error"}'

번외. winston으로 로깅하고 있다면..

splat 함수를 옵션으로 설정하면, JSON.stringify 하지 않고 객체 전체를 파일로 작성할 수 있습니다.

// winston 설정
winston.createLogger({
  format: combine(
    timestamp({
      format: "YYYY-MM-DD HH:mm:ss.SSS",
    }),
    label({ label: constants.PROJECT_NAME }),
    splat(), // 이 부분!!
    logFormat,
  ),
});

실제 사용은 아래와 같이 합니다.

const error = new Error('error test');
logger.error('%s', error);


의견은 언제든 댓글로 남겨주세요. 🙂

profile
미래의 내가 참고하려고 모아가는 중 :)

0개의 댓글