programing

TypeScript 사용자 지정 오류 클래스

batch 2023. 4. 6. 21:22
반응형

TypeScript 사용자 지정 오류 클래스

코어를 확장하여 TypeScript에서 자체 오류 클래스를 만들고 싶습니다.Error에러 처리 및 커스터마이즈된 리포트를 제공합니다.예를 들어, I want to create a name.HttpRequestErrorurl, 응답 및 본문이 컨스트럭터에 전달된 클래스는 상태 코드 500 메시지와 함께 http://example.com에 대한 HTTP 요청으로 응답하지 못했습니다. 뭔가 잘못되어 스택트레이스가 올바르게 되어 있습니다.

TypeScript에서 핵심 오류 클래스를 확장하는 방법SO: TypeScript에서 호스트 오브젝트를 확장하는 방법(오류 등)은 이미 확인했지만 이 솔루션은 작동하지 않습니다.TypeScript 1.5.3 사용

좋은 생각 있어요?

TypeScript 2.1은 오류와 같은 빌트인 확장과 관련하여 획기적인 변경 사항을 가지고 있습니다.

TypeScript 브레이크 변경 문서

class FooError extends Error {
    constructor(msg: string) {
        super(msg);

        // Set the prototype explicitly.
        Object.setPrototypeOf(this, FooError.prototype);
    }

    sayHello() {
        return "hello " + this.message;
    }
}

다음으로 다음을 사용할 수 있습니다.

let error = new FooError("Something really bad went wrong");
if(error instanceof FooError){
   console.log(error.sayHello());
}

1.6이 될 때까지, 저는 저만의 확장 가능한 수업을 만들고 있었습니다.

class BaseError {
    constructor () {
        Error.apply(this, arguments);
    }
}

BaseError.prototype = new Error();

class HttpRequestError extends BaseError {
    constructor (public status: number, public message: string) {
        super();    
    }
}

var error = new HttpRequestError(500, 'Server Error');

console.log(
    error,
    // True
    error instanceof HttpRequestError,
    // True
    error instanceof Error
);

TypeScript 1.8을 사용하고 있으며, 커스텀에러 클래스를 사용하는 방법은 다음과 같습니다.

의외의입력.ts

class UnexpectedInput extends Error {

  public static UNSUPPORTED_TYPE: string = "Please provide a 'String', 'Uint8Array' or 'Array'.";

  constructor(public message?: string) {
    super(message);
    this.name = "UnexpectedInput";
    this.stack = (<any> new Error()).stack;
  }

}

export default UnexpectedInput;

마이앱

import UnexpectedInput from "./UnexpectedInput";

...

throw new UnexpectedInput(UnexpectedInput.UNSUPPORTED_TYPE);

TypeScript 버전이 1.8보다 오래된 경우 선언해야 합니다.Error:

export declare class Error {
  public message: string;
  public name: string;
  public stack: string;
  constructor(message?: string);
}

Typescript 3.7.5의 경우 이 코드는 올바른 스택 정보를 캡처하는 커스텀에러 클래스를 제공했습니다.메모instanceof동작하지 않기 때문에 사용하고 있습니다.name대신

// based on https://gunargessner.com/subclassing-exception

// example usage
try {
  throw new DataError('Boom')
} catch(error) {
  console.log(error.name === 'DataError') // true
  console.log(error instanceof DataError) // false
  console.log(error instanceof Error) // true
}

class DataError {
  constructor(message: string) {
    const error = Error(message);

    // set immutable object properties
    Object.defineProperty(error, 'message', {
      get() {
        return message;
      }
    });
    Object.defineProperty(error, 'name', {
      get() {
        return 'DataError';
      }
    });
    // capture where error occured
    Error.captureStackTrace(error, DataError);
    return error;
  }
}

가지 다른 대안과 그 이유에 대한 토론이 있다.

https://www.npmjs.com/package/ts-custom-error에 이를 위한 깔끔한 라이브러리가 있습니다.

ts-custom-error에러 커스텀 에러를 간단하게 작성할 수 있습니다.

import { CustomError } from 'ts-custom-error'
 
class HttpError extends CustomError {
    public constructor(
        public code: number,
        message?: string,
    ) {
        super(message)
    }
}

사용방법:

new HttpError(404, 'Not found')

이것은 현재 최신 버전의 타이프스크립트(4.7.3)에서는 문제가 되지 않는 것 같습니다.

import { expect } from 'chai';
import { describe } from 'mocha';

class MyError extends Error {}

describe('Custom error class "MyError"', () => {
  it('should be an instance of "MyError"', () => {
    try {
      throw new MyError();
    } catch (e) {
      expect(e).to.be.an.instanceOf(MyError);
    }
  });
});

어떤 버전이 동작을 변경했는지 알 수 없지만 2.1에서 이 테스트는 실패합니다.

언급URL : https://stackoverflow.com/questions/31626231/custom-error-class-in-typescript

반응형