TS 를 ES5 로 내리면 Error 를 상속한 클래스의 instanceof 가 깨진다 — super() 직후 프로토타입을 직접 맞춘다. ES2015 이상 타깃이면 필요 없다.1
class CustomError extends Error {
name = 'CustomError'
constructor(message?: string) {
super(message)
Object.setPrototypeOf(this, CustomError.prototype)
}
}
try {
throw new CustomError('This is a custom error message.')
} catch (error) {
if (error instanceof CustomError) {
console.log('CustomError occurred:', error.message)
console.log('Error name:', error.name)
} else {
console.log('An error occurred:', error)
}
}
- https://github.com/Alex-D/check-disk-space/blob/main/src/errors/invalidPathError.ts
- https://github.com/adriengibrat/ts-custom-error/blob/main/src/custom-error.ts
- 📘 타입스크립트 커스텀 Error 처리하기
- Handling errors like a pro in TypeScript | by Kolby Sisk | Udacity Eng & Data
Footnotes
-
TypeScript Breaking Changes — TypeScript 2.1: “constructor functions for
Error,Array, and the like use ECMAScript 6’snew.targetto adjust the prototype chain; however, there is no way to ensure a value fornew.targetwhen invoking a constructor in ECMAScript 5.” / “As a recommendation, you can manually adjust the prototype immediately after anysuper(...)calls.” ↩