...

/

Observable Errors

Observable Errors

Learn how to catch errors in an Observable stream, including how to use catchError within an Observable stream itself.

Observable exceptions

What happens when something goes wrong within an Observable stream?

Obviously, we will need a mechanism to catch these errors so that we can do something sensible with them.

As an example of a faulty Observable stream, consider the following code:

Press + to interact
// Interface definition for a property 'value' of type number
interface IValue {
value: number
}
// Interface definition for an optional property 'id' of type IValue
interface INestedObj {
id?: IValue;
}
// Create an observable 'objEmit' of type INestedObj and initialize it with 3 objects
const objEmit : Observable<INestedObj> = of(
{ id: { value: 1 } }, // First object with id and value property
{}, // Second object with no properties
{ id: { value: 2 } } // Third object with id and value property
);

Here, we start with two interfaces named IValue and INestedObj.

  • The IValue interface on lines 2 – 4 has a property named value of type number.

  • The INestedObj interface on lines 7 – 9 has a single optional parameter named id of type IValue.

  • We then create an Observable named objEmit on lines 12–16 that emits three values:

    • The first value has the nested structure described by the INestedObj interface.
    • The second is a blank object.
    • The third value also has the nested structure described by the INestedObj interface.

Now, consider the following Observable stream:

Press + to interact
// This code defines a function that subscribes to an observable and extracts the ID value of an object.
// Define an observable and apply the map operator to extract the ID value of an object.
const returnIdValue = objEmit.pipe(
map((value: INestedObj) => {
return value.id!.value;
})
);
// Subscribe to the observable and log the extracted ID value to the console.
returnIdValue.subscribe((value: number) => {
console.log(`received ${value} `)
});
  • We have an Observable stream named returnIdValue on lines 4–8 ...