// Importing rxjs package import { Observable } from 'rxjs'; // Throwing an error in the Observable const observable = Observable.throw('An error occurred.'); // Subscribing to the Observable observable.subscribe( value => console.log(value), error => console.error(error), () => console.log('Completed.') );
// Importing rxjs package import { throwError } from 'rxjs'; // Creating a custom error object const customError = { message: 'A custom error occurred.', code: 500 }; // Throwing the custom error in the Observable const observable = throwError(customError); // Subscribing to the Observable observable.subscribe( value => console.log(value), error => console.error(error), () => console.log('Completed.') );In this example, we use the throwError operator from the rxjs package to throw a custom error object when subscribed to. We then subscribe to the Observable and log the error object to the console. Package library: rxjs