Angular

Last Updated: 9/5/2023

Throwing Application Specific Errors

  • Components should not check the status of the response and compare with status code instead it is the work of service
  • The Component, instead of working with response object should work with application domain object not specific to http protocol
  • Observables is part of third-party library called reactive extensions. This type has a bunch of useful extensions called operators
  • Create App specific error classes

common/app-error.ts

export class AppError {
	constructor(public originalError){
	}
}

#### common/not-found-error.ts
export class NotFoundError extends AppError {
}

common/bad-input.ts

export class BadInput extends AppError {
}
  • Throw app specific error

post.service.ts


import { Observable } from 'rxjs/observable"
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
deletePost
	.catch((error: Response) => {
		if(error.status == 404) {
			return Observable.throw(new NotFoundError())
		}
		return Observable.throw(new AppError(error))
	})
createPost
	.catch((error: Response) => {
		if(error.status == 400) {
			return Observable.throw(new BadInput(error.json()))
		}
		Observable.throw(new AppError(error))
	})
  • Handle app specific error

posts.component.ts

this.subscribe.deletePosts()
.subscribe(
	() => {},
	(error) => {
		if(error instanceOf NotFoundError)
			alert("the post is already deleted");
		else 
			alert("Unexpected error occured");
		}	
	}
)
this.service.createPosts(post).
	subscribe(
		() => {}, 
		error => {
			if(error instanceOf BadInput) {
				alert("bad request");
			}
			else {
				alert("Unexpected error occured");
			}
		}
	)