For an angular project I am given an url that contains a list of all api paths (discover path). In my application I want to call the discover path and save the results in a list. My code:
discover(): Observable<ApiLink[]> {
if (this.links) {
return of(this.links);
}
try {
console.log('calling :', URL);
return this.http.get<{links: ApiLink[]}>(URL, {headers: this.headers}).pipe(
map(response => {
this.links = response.links;
return this.links;
}),
catchError(some_error => {
console.log('error ', some_error);
throw new Error('failed to discover the api.');
}),
);
} catch (e) {
console.log('api discover failed ', e);
throw new Error('failed to discover the api.');
}
}
My question is when does it go to catchError and when to catch? If the call is succesfull but returns a error 500 does it go the the catcherror is is it going to catchError or is it a valid response (the call worked right)? And how should the calling method handle the possible error. Is it correct when I call with catcherror:
// we give a string that relates to a path e.g. 'user' returns someurl.com/api/users
url(rel: string, params?: object): Observable<string> {
return this.discover().pipe(
map(links => {
const link = links.find(item => item.rel === rel);
if (link) {
return link.href;
} else {
throw new Error(`IXapi entry "${rel}" was not found.`);
}
}),
catchError( errormessage => {
console.log('error inside url ', rel, ' error:', errormessage);
throw errormessage;
})
);
}
Or should it be with a try catch.
url(rel: string, params?: object): Observable<string> {
console.log('url: ', rel);
try{
return this.discover().pipe(
// do stuff
);
}catch(e)
{
console.log('do some stuff because we have an error');
throw e;
}
}
In short when should the try/catch vs catcherror be used and how should I catch the error thrown in a catcherror/try catch from a calling method?
In Synchronous programming we use traditional try catch block to catch any errors that are thrown.
try {
// synchronous operation
const httpResponse = getHttpResponseSync('/api/getUsers');
}
catch(error) {
// handle error
}
But when its asynchronous programming like an HTTP request we cannot rely on this try catch block,
So Rxjs provides this catchError a function that takes in an input Observable, and outputs an Output Observable.
That function is expected to return an Observable which is going to be a replacement Observable for the stream that just errored out.
as per your first question! It will always go to catchError because http.get an observable which makes it async
Refer https://www.intertech.com/Blog/angular-best-practice-rxjs-error-handling/
Try catch is used for normal catching error in js code
Like this
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
catchError is used for observable error catching
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
//emit error
const source = throwError('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With