Upgrade to Pro — share decks privately, control downloads, hide ads and more …

HRMOSにおけるAngularのエラーハンドリングについて

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

 HRMOSにおけるAngularのエラーハンドリングについて

Angularアプリの簡単・強力なエラーハンドリングの仕組みを紹介します

Avatar for deepblue-will

deepblue-will

June 13, 2019
Tweet

More Decks by deepblue-will

Other Decks in Technology

Transcript

  1. export class ApplicationError extends Error { constructor(message: string) { super(message);

    // instanceofを使えるようにする Object.setPrototypeOf(this, ApplicationError.prototype); } }
  2. // Usage const sampleFn = (type: 'A' | 'B') =>

    { switch (type) { case 'A': // anything break; case 'B': // anything break; default: throw new ApplicationError('Unsupported Type'); } };
  3. export class RequestError extends Error { constructor(private errorResponse: HttpErrorResponse, message:

    string) { super(message); // instanceofを使えるようにする Object.setPrototypeOf(this, RequestError.prototype); } get statusCode(): number { return this.errorResponse.status; } }
  4. export class HandleErrorInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler):

    Observable<HttpEvent<any>> { return next .handle(req) .pipe( catchError( (e: HttpErrorResponse) => throwError(new RequestError(e, getErrorMessage(e)))) ); } }
  5. export function provideHttpInterceptors() { return [{ provide: HTTP_INTERCEPTORS, useClass: HandleErrorInterceptor,

    multi: true }]; } @NgModule({ providers: [ provideHttpInterceptors(), ], }) export class MyModule {}
  6. @Injectable({ providedIn: 'root' }) export class MyErrorHandler implements ErrorHandler {

    handleError(e: any) { if (e instanceof RequestError) { // エラー用のトーストを表示 this.showErrorToast(e.message); } else if (e instanceof ApplicationError) { // Sentryにエラー内容を送信 Sentry.captureException(e); } else { this.showErrorToast('想定外のエラーが発生しました。'); Sentry.captureException(e); } } }
  7. handleError(e: any) { if (e instanceof RequestError) { // リクエストエラーが起こってるのにここを通らない

    this.showErrorToast(e.message); } } // ↓ handleError(e: any) { if (e.rejection instanceof RequestError) { // rejectionにErrorが入ってることがある this.showErrorToast(e.message); } }
  8. handleError(e: any) { if (e instanceof RequestError) { // トーストが表示されない

    this.showErrorToast(e.message); } } // ↓ handleError(e: any) { if (e.rejection instanceof RequestError) { // NgZoneをDIして変更通知してあげる this.ngZone.run(() => this.showErrorToast(e.message)) } }
  9. handleError(e: any) { if (e instanceof RequestError) { // hogeServiceがDIできてない

    this.hogeService.hoge(); } } // ↓ handleError(e: any) { if (e.rejection instanceof RequestError) { // Injectorでgetする const hogeService = this.injector.get(HogeService); hogeService.hoge(); } }