Throwing Application-specific Errors .catch

As I’m going through Mosh’s angular course I’ve been able to adjust up to this point with some of the outdated syntax. I’m running into an issue on Lesson 13 under “Consumming HTTP Services”, lecture Throwing application specific errors. The gist is I have a method that returns the output from a deleting a post.

deletePost(id) {
console.log(id);
return this.http.delete(this.url + ‘/’ + id);
}

He imports “import ‘rxjs/add/operator/catch’;”

and that allows him to adjust the method to
deletePost(id) {
console.log(id);
return this.http.delete(this.url + ‘/’ + id)
.catch( (error: Response) => {
// Stuff in here
);
}

That does not appear to work in angular 10. Can someone give me some direction? Do I need to switch to catchError? Does the newer version use .subscribe and then I can block out the error from there? I’m pretty fresh with this so I’m not sure what the right way forward is? Below is the full code to give a little context. Thank you for your help!

File post.service.ts

import { HttpClient } from ‘@angular/common/http’;
import { Injectable } from ‘@angular/core’;

import ‘rxjs/add/operator/catch’;

@Injectable({
providedIn: ‘root’
})
export class PostService {

private url = ‘http://jsonplaceholder.typicode.com/posts’;

httpOptions: {
responseType: ‘json’
};

constructor(private http: HttpClient) { }

getPosts() {
return this.http.get(this.url,this.httpOptions);
}

createPost(post) {
return this.http.post(this.url,JSON.stringify(post));
}

updatePost(post) {
return this.http.patch(this.url + ‘/’ + post.id, JSON.stringify({ isRead: true }));
}

deletePost(id) {
console.log(id);
return this.http.delete(this.url + ‘/’ + id);
}

}

1 Like

As usual, the moment I posted something I found my solution! I found I need to wrap it in .pipe() and then use CatchError…

deletePost(id) {
console.log(id);
return this.http.delete(this.url + ‘/’ + id)
.pipe(
catchError( (error: Response) => {
if (error.status === 404)
return Observable.throw(new NotFoundError());
return Observable.throw(new AppError(error));
})
);
}

2 Likes

import { map, retry, catchError } from ‘rxjs/operators’;

import { Observable, throwError } from ‘rxjs’;

delete(id: number): Observable {

return this.http

  .delete(this.url + '/' + id)

  .pipe(catchError(this.handleError));

}

3 Likes

This is Angular 11 syntax

2 Likes

private handleError(error: Response) {

if (error.status === 400) return throwError(new BadInput(error.json()));

if (error.status === 404) return throwError(new NotFoundError());

return throwError(new AppError(error.json()));

}

3 Likes