angular try catch vs catcherror
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));