Angular, Throwing Application-specific Errors

Here you will find simple example of Throwing Application-specific Errors

GitHub

https://github.com/szalek/AngularAppSpecificErrors

Setup

ng new AngularAppSpecificErrors
ng g s post
ng g c post

Run app

ng serve --watch true --poll 100 --host 0.0.0.0 --port 4200 -o

Docker

This step is not required, but if you don’t want to install node on you local you can use docker
http://blog.michalszalkowski.com/docker/angular-cli-in-docker/

Project structure

Error type declaration (/src/app/core/app-error.ts)

export interface AppError {
  code: number;
  message: String;
}

export class AppBaseError implements AppError {

  public code: number = 0;
  public message: string = "unknow";

  constructor(public error: Response) {
    this.message = error.statusText;
  }
}

export class NotFoundError extends AppBaseError {
  public code: number = 404;
}

export class ServerError extends AppBaseError {
  public code: number = 505;
}

export class CrazyShitError extends AppBaseError {

}

Service where we are use custom errors (/src/app/post/post.service.ts)

import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/catch'
import 'rxjs/add/observable/throw';
import {CrazyShitError, NotFoundError, ServerError} from "../core/app-error";

@Injectable()
export class PostService {

  private url = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: HttpClient) {
  }

  getPosts(): any {
    return this.http.get(this.url)
      .catch((error: Response) => {

        if (error.status === 404) {
          return Observable.throw(new NotFoundError(error));
        }

        if (error.status === 500) {
          return Observable.throw(new ServerError(error));
        }

        return Observable.throw(new NotFoundError(error));

      });
  }
}