Reputation: 21
I've been learning Angular 6 and I had a question about the subscribe method and error handling.
So a basic use of the subscribe function on an observable would look something like this:
this.myService.myFunction(this.myArg).subscribe(
// Getting the data from the service
data => {
this.doSomethingWith(data);
},
err => console.log('Received an error: ', err),
() => console.log('All done!')
);
So an error in this case might be a 500 error or something, but I'm wondering if there's a way to send my data from my back end (I'm using PHP) such that the subscribe function will recognise it as an error. For example, my app allows users to create a list of items from a specific finite set (the set of all Pokemon in my case) so if he/she tries to add a pokemon that doesn't exist, I want my back end to return an error. Currently I'm returning a JSON object like this: { "error" => "you did something wrong" }
and I handle it in the first argument of my subscribe function. I suppose s fine, but if there's something in place for proper error handling I would think it would be best to utilise that.
Cheers!
Upvotes: 1
Views: 174
Reputation: 7231
Try something like this:
import {
HttpEvent,
HttpHeaders,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHandler,
HttpRequest
} from '@angular/common/http';
this.myService.myFunction(this.myArg).subscribe(
// Getting the data from the service
data => {
this.doSomethingWith(data);
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
switch (err.status) {
case 400:
console.log("400 Error")
break;
case 401:
console.log("401 Error")
break;
case 500:
console.log("500 Error")
break;
}
}
);
Upvotes: 1