Differentiating between catchError, throwError, new Error and throw new Error.
In this quick guide, I am collating the different ways to create errors and handling them in Javascript and TypeScript applications.
catchError (Rxjs)
It is a Rxjs operator used to catch errors. It is similar to the catch()
method on Promises
and the catch block in try…catch
. catchError
, as the name implies, catches errors so that the application does not crash and returns a fallback value as an observable.
const failingHttpRequest$ = new Observable((subscriber) => {
setTimeout(() => {
subscriber.error(new Error('Timeout'));
}, 3000);
});
console.log('App started...');
failingHttpRequest$
.pipe(
catchError((err) => { // catch error
return of('Fallback value'); // return fallback observable
})
)
.subscribe({
next: (v) => {
console.log('The observable value:', v); //Logs => The observable value: Fallback value
},
});
throwError (Rxjs)
It is a Rxjs creation operator that creates an error observable that emits an error immediately and does nothing else after that. The error only throws when the error observable is subscribed to.
import { throwError } from 'rxjs';
throwError(
() => {
return new Error('My error');
}
).subscribe() // throws error
To throw an error that does not need a subscription within an observable. You can use the normal throw
like below.
throw new Error (JS/TS)
Immediately throws the instantiated error object. If not used inside a try…catch
statement, then the application will crash.
try {
throw Error('My error')
} catch (error) {
console.log('I have catched the error', error);
}
new Error (JS/TS)
Creates an error object that can be thrown.
let myError = new Error("This is my error message");
throw myError; // throws the error
throw (JS/TS)
The throw
keyword is reserved to throw user defined exceptions and to throw custom errors created with the Error object or errors that extends it. The throw
keyword can also throw errors with literals.
throw {message: 'Error message', code: 'ER'}
throw 'Some error'
throw 400
throw Error('Some error')
throw new Error('Some error')
throw new MyCustumeError()
What are other mechanism or constructs for error handling? What else do you think I’ve missed in this guide?