Currently, I'm working through an Angular tutorial and facing a challenge in the error-handling section. Despite my efforts to trigger an error with incorrect data in a HttpClient.delete()-request, I am unable to force one.
To provide some context, I am retrieving my data (posts) from http://jsonplaceholder.typicode.com/posts.
Even after attempting to input invalid ids into the delete-function at various points, such as out-of-bound ids or '1' which should be deletable upon two button clicks, no errors are being generated.
Instead of throwing an error, the functionality is performing as expected by clearing out the posts-list and precisely deleting the selected posts upon clicking.
I went further to simplify the process by eliminating error-services and consolidating actions within the posts-component without success.
View the excerpts below for reference:
posts.component.ts
import { BadInputError } from './../common/bad-input';
import { NotFoundError } from './../common/not-found-error';
import { PostService } from './../services/post.service';
import { Component, Input, OnInit } from '@angular/core';
import { AppError } from '../common/app-error';
@Component({
selector: 'posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
posts: any[];
constructor(private service: PostService) { }
// ...
deletePost(post) {
this.service.deletePost(post.id).subscribe(
response => {
console.log(response);
let index = this.posts.indexOf(post);
this.posts.splice(index, 1);
},
(error: AppError) => {
if (error instanceof NotFoundError)
alert('This post has already been deleted.');
else {
alert('An unexpected error occured.');
console.log(error);
}
}
);
console.log(this.posts);
}
}
posts.component.html
<ul class="list-group">
<li
*ngFor="let post of posts"
class="list-group-item">
<button
(click)="deletePost(post)"
class="btn btn-default btn-sm">
Delete
</button>
{{ post.title }}
</li>
</ul>
post.service.ts
export class PostService {
private url = 'http://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }
// ...
deletePost(id) {
return this.http.delete(this.url + '/' + id)
.pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404)
// throw Observable.throw(new NotFoundError);
throw throwError(error);
//return Observable.throw(new NotFoundError);
else
return Observable.throw(new AppError(error));
})
);
}
}
app-error.ts
export class AppError {
constructor(public originalError?: any) {}
}
not-found-error.ts
import { AppError } from './app-error';
export class NotFoundError extends AppError {}
bad-input.ts
import { AppError } from './app-error';
export class BadInputError extends AppError {}
If anyone can shed light on where I might be going wrong and how I can intentionally trigger errors to test the application, it would be greatly appreciated.
Warm regards