LoginSignup
6
1

More than 5 years have passed since last update.

Node.jsのTypeScriptにおけるエラーの定義はinterfaceだった

Posted at

概要(TL;DR)

typeScriptではエラーオブジェクトはインターフェースとして定義されていました。

使っているTypeScriptのバージョン

typescript 3.2.2

実際の定義

lib.es5.d.ts
interface Error {
    name: string;
    message: string;
    stack?: string;
}

つまりこのinterfaceをimplementsで実装してやればネイティブのエラーを侵食することなくオリジナルのエラーを実装できるってことですね。

実際にエラークラスを実装してみた

Rest APIエラー処理に利用したかったので、ネイティブのErrorインターフェースをimplementsした、各エラーの基底となる抽象クラスを作り、そのクラスを継承して各エラークラスを実装する形にしました。

CommonError.ts
export abstract class CommonError implements Error {
  name: string;
  code: number;
  message: string;
  body?: any;
  // 最終的にjsonでレスポンスするのでそのための変換関数
  public toJson(): any {
    return {
      name: this.name,
      code: this.code,
      message: this.message,
      body: this.body
    }
  }
}
MyError.ts
import { CommonError } from 'path/to/commonError';

export class MyError extends CommonError {
  constructor (){
    super();
    this.name = 'MyError';
    this.code = 500;
    this.message = 'MyError is occurred.'
  }
}

まとめ

  • ネイティブのエラーの定義はinterface
  • なのでそれをimplementsする
  • 各エラーの基底となるクラスを作り、それを継承して各エラークラスを作ろう
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1