Handling Errors in the ViewModel

OK, this time round I’m going to look at what I want my ViewModel to do when things go wrong. If, for instance, the repository for my ToDoItems throws an exception.

Obviously I don’t want my app to crash if that happens, so I need to catch the possible exceptions and deal with them gracefully. In this instance I think I want to display an error message instead of my list of ToDoItems. What I’ll need for that is a) a label to display said error message and b) some way of toggling the visibility of my error message and list.

I can implement a) by simply adding a string property, and b) by binding the visibility of said elements to a boolean property in my ViewModel.

Now I only need to put my repository code in a try-catch block and handle exceptions:

Ok, right now I’m using a catch-all exception handler here, which is not great, but right now it’s all I need. I reserve the right to change my mind later.

In other news, I initialise my IsFaulted and ErrorMessage properties optimistically in my constructor, and only change them if things go horribly wrong while trying to get the data from the repository.

With that in place I can now add another test:

This time round I’m setting my repo mock up to throw an exception (asynchronously!) whenever the GetAsync method is called, and assert that my IsFaulted and ErrorMessage properties have the correct values.

…and now I think that’s enough testing for now. Time to go back to the app itself – in the next article!

Leave a Reply

Your email address will not be published. Required fields are marked *