Error
ErrorはJavaScriptの組み込みAPIのひとつで例外を取り扱うためのオブジェクトです。
Errorオブジェクトの作り方
Errorオブジェクトを作るにはErrorクラスをnewします。例外を投げるためにはthrowを使います。
tsthrow newError ();
tsthrow newError ();
JavaScriptではErrorクラス以外も例外としてthrowできる
とはいえ、JavaScriptでは例外を表すErrorクラスとそのサブクラスだけをthrowできるのではなく、どのような値もthrowできます。
tsthrow "id is not string!";
tsthrow "id is not string!";
Errorクラスのサブクラス
組み込みAPIとしてErrorには次のサブクラスがあります。
- EvalError
- InternalError
- RangeError
- ReferenceError
- SyntaxError
- TypeError
- URIError
またErrorを拡張し独自のサブクラスを定義することもできます。
tsclassCustomeError extendsError {public constructor(message ?: string) {super(message );}}consterr :CustomeError = newCustomeError ("FAILED!");console .log (err .name );console .log (err .message );console .log (err .stack );
tsclassCustomeError extendsError {public constructor(message ?: string) {super(message );}}consterr :CustomeError = newCustomeError ("FAILED!");console .log (err .name );console .log (err .message );console .log (err .stack );
例外を捕捉する
throwされた例外はcatchで捕捉できます。ですが先ほど述べたようにJavaScriptはどのような値もthrowできるのでcatchした値の型は定まらずany型かunknown型として解釈されます。どちらの型になるかはtsconfig.jsonのuseUnknownInCatchVariablesの設定により決まります。
📄️ useUnknownInCatchVariables
例外捕捉catch(e)のeをunknown型として扱う
もし捕捉した値があるクラスのインスタンスまたはある型であるかを判定したい場合はinstanceof, keyofあるいは型ガードを使います。
tstry {// ...} catch (e ) {if (e instanceofError ) {// ...}}
tstry {// ...} catch (e ) {if (e instanceofError ) {// ...}}