JavaScriptã§ã«ã¹ã¿ã ä¾å¤ã¯ã©ã¹ãä½ããããªã¨æã£ããã
ããã©ãã ã£ãã®ã§ããã®æ調ã¹ãã¨ãã®åå¿é²ã
以ä¸ããããåèã«ãªã£ã(´Ïï½)
ã»ä¾å¤å¦ç â ä»äºã§ããã«ä½¿ããTypeScript ããã¥ã¡ã³ã
ã«ã¹ã¿ã ä¾å¤
ãããªæãã
export class CustomError extends Error { constructor(e?: string) { super(e); this.name = new.target.name; // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } // https://future-architect.github.io/typescript-guide/exception.html // ä¸è¨ã®è¡ã¯TypeScriptã®åºåã¿ã¼ã²ãããES2015ããå¤ãå ´å(ES3, ES5)ã®ã¿å¿ è¦ Object.setPrototypeOf(this, new.target.prototype); } }
ãã£ã¼ã«ãã追å ãããã¨ãã«ã¯ãconstractorã«è¿½å ããã°OKã
class NetworkAccessError extends CustomError { constructor(public statusCode: number, e?: string) { super(e); } }
ä¾å¤ãåãåã
ä¾å¤ã®catchç¯å
ã§ãinstanceof
ã使ãã°ãå¤å¥ã§ããã
try { hoge(); } catch (e) { if (e instanceof NetworkAccessError) { console.log(`statusCode=${e.statusCode}`) } else { console.log(e) } }
以ä¸!!