#author("2021-03-21T12:15:58+09:00","default:ryuichi","ryuichi")
#author("2021-03-21T12:16:25+09:00","default:ryuichi","ryuichi")
* カスタムエラー [#d0e817be]

** ES2015 (ES6)以降 [#s1d83966]

 class MyError extends Error {
   constructor(message) {
     super(message);
     this.name = new.target.name;          // (1)
   }
 }
 
 const err = new MyError("ERROR-MESSAGE");
 console.log(err.toString());              // (2)
 if (err instanceof MyError){
   console.log("OK");
 }
 
 ↓
 ↓
 ↓  
 
 MyError: ERROR-MESSAGE
 OK

- (1) nameの指定をしないと、
- (2) のtoString()が '''MyError: ERROR-MESSAGE'''ではなく'''Error: ERROR-MESSAGE'''になる

** 参考 [#i1cfafbd]

- https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Error/name
- https://future-architect.github.io/typescript-guide/exception.html

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS