Error Handling
NGXS uses Angular's default ErrorHandler
class, so if an action throws an error, Angular's ErrorHandler
is called. You can easily override this flow by providing your own handler like so:
Handling errors within an @Select
@Select
Let's take a look at the below example:
The catch is that when resetting the entire state, the object will no longer have those deeply nested properties (state.count.number.value
). Given the following code:
RxJS will automatically complete the stream under the hood if any error is thrown.
You have to disable suppressing errors using the suppressErrors
option:
This option allows to track errors and handle them.
Why does RxJS unsubscribe on error?
RxJS design guidelines provides a great explanation of this behavior.
Handling errors within an @Action
@Action
When you define an @Action you can handle error within the action and if you do so, the error will not propagate to Angular's global ErrorHandler
, nor the dispatch
Observable. This applies to both sync and async types of Actions.
Handling errors after dispatching an action
If an unhandled exception is thrown inside an action, the error will be propagated to the ErrorHandler
and you can also catch it subscribing to the dispatch
Observable. If you subscribe to the dispatch
Observable the error will be caught twice, once in the ErrorHandler and on your dispatch
handle.
It is recommended to handle errors within @Action
and update state to reflect the error, which you can later select to display where required.
You can play around with error handling in this following stackblitz
Last updated