'Angular 7 http error handling not working properly
I am trying to handle 422 error handling on my HTTP request. But somehow the error block doesn't run in the service using catchError operator. If there is no error the code is just working fine. I want to display error message on my page. But angular is only throwing error in console and not running the error block. Here is my http error response:

And here is the error I am getting only in console.
I want to display error message on my page. Here is my HTTP request.
renderPlugin(id): Observable<any> {
return this.http
.get(`${environment.kbUrl}/${id}?_as_json=1&_nbp=1`, {
responseType: "text",
observe: "response"
})
.pipe(
catchError((res: HttpErrorResponse) => {
console.log(JSON.stringify(res));
this.toastr.error("error", JSON.stringify(res));
return throwError(JSON.stringify(res));
})
);
}
And here is my method to subscribe to the it.
this.pluginsService.renderPlugin(this.currentId).subscribe(res =>{
this.currentString = res.body;
this.plugin = this.currentString.data.content;
console.log(this.plugin);
},
err =>{
this.plugin = err;
});
Solution 1:[1]
Probably you have an interceptor that catches the error. If you need to handle errors in the interceptor, you may consider throwing them after your handling logic.
Solution 2:[2]
Try removing this code from your Http call:
.pipe(
catchError((res: HttpErrorResponse) => {
console.log(JSON.stringify(res));
this.toastr.error("error", JSON.stringify(res));
return throwError(JSON.stringify(res));
})
)
And handle your error inside the error block of your subscribe method.
this.pluginsService.renderPlugin(this.currentId).subscribe(
res => {
this.currentString = res.body;
this.plugin = this.currentString.data.content;
console.log(this.plugin);
},
err => {
// Handle the error here
// like displaying toast using the error message received from server
this.plugin = err;
}
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maxim Krabov |
| Solution 2 | Kush Grover |

