Recently, as I dive into learning Angular 6, a question has arisen regarding the subscribe method and error handling.
A typical use of the subscribe function on an observable typically appears like this:
this.myService.myFunction(this.myArg).subscribe(
// Retrieving data from the service
data => {
this.doSomethingWith(data);
},
err => console.log('An error occurred: ', err),
() => console.log('Process complete!')
);
In this scenario, an error could be a 500 status code or similar, but my curiosity lies in finding a way to structure the data sent from my backend (utilizing PHP) so that the subscribe function can interpret it as an error. For instance, envision an application where users build a list of items from a defined finite set (let's say, the collection of all Pokemon), if a user tries to add a non-existing Pokemon, I want the backend to signal an error. Presently, I return a JSON object like this:
{ "error" => "you did something wrong" }
and handle it within the first argument of my subscribe function. While this works fine, I ponder if there are established methods for efficient error handling that would be worth implementing.
Cheers!