본문 바로가기

Backend/Node.js

Error handling과 custom Error 생성

Error handling

  • 다른 언어에서 제공하는 try/catch 구문이 자바스크립트에서도 존재
  • 자바처럼 특정 클래스/메서드 사용할때 강제하는 것도 아니라서 클라이언트 개발할때 거의 쓸일이 없었다.(그냥 if문으로 처리했었다.)
  • 백엔드서버에서 사용하다보면 에러났을 경우에 어떻게 처리할것인지와 어떤 에러를 내서 로그에 기록할 것인지가 중요
  • 자바에서 Exception 상속 받아서 사용자 정의 예외 만들던것처럼 자바스크립트에서는 클래스나 함수(화살표함수는 X)로 커스텀 에러 만들수가 있다.

커스텀에러와 try/catch

  • 생성자함수를 통해 커스텀 에러 정의 가능(function 혹은 class로 정의)
  • 그러므로 arrow function으로는 불가능(TypeError: CustomError is not a constructor)
/* 아래의 소스는 콘솔에서 다음과 같은 결과를 출력해준다.
  CustomError {
  item: 'study.ppt',
  type: 'NotImageFileException',
  message: 'NotImageFileException: study.ppt is not an image file'
  }
*/

/*** 정해놓은 확장자와 일치하지 않는 파일명인 경우 에러 발생 ***/
function CustomError(item){
  this.item = item;
  this.type = 'NotImageFileException';
  this.message = `${this.type}: ${item} is not an image file`;
}

try {
  const whitelist = ['.jpg', '.png', '.gif'];
  const images = ['fast.jpg', 'study.ppt'];

  const isValidImageFiles = (data) => {
    return data.map(item => {
      const ret = whitelist.some(_item => item.endsWith(_item));
      if(ret) return {isPass: true, item: item};
      return {isPass: false, item: item};;
    });
  }

  isValidImageFiles(images).forEach(v => {
    if(!v.isPass) throw new CustomError(v.item);
  });

} catch (e) {
  console.error(e)
}

'Backend > Node.js' 카테고리의 다른 글

[multer] 파일업로드  (0) 2020.02.11
[가비아] Node.js 웹호스팅 세팅  (0) 2020.01.27
[NVM] Node.js 설치  (0) 2020.01.23
[graphQL] rest API와 차이점, Apollo Server로 맛보기  (0) 2020.01.10
Node.js와 Event Roof  (0) 2020.01.02