C# – Shoud I throw exceptions to UI layer or handle them in the VM layer

cdesigndesign-patternserror handlingmobile

Consider the following method:

    public async Task LoginAsync()
    {
        if (!CanLoginAsyncExecute()) throw new ValidationException();

        try
        {
            StartLoading();
            await _authenticationService.LoginAsync(Email, Password);
        }
        catch (LoginException e)
        {
            _logger.Error(e);
            throw;
        }
        catch (ServiceException e)
        {
            _logger.Error(e);
            throw;
        }
    }

Im having a hard time deciding should I throw my exceptions to the UI layer that calls this method or handle the errors here? It's a personal xamarin project so I could handle the error in the VM (using dialogs or something). Is it a good practice to "silently" handle errors in the business logic layer and rethrow the exceptions? So pretty much if the method doens't throw anything, the login is successful? Or should I be returning a boolean or something to indicate the login was successful?

Best Answer

A login error is not unexpected. It is probable that unauthorised users might try to access the system. It is also possible ( even quite common ) that regular users make typos or even pick the wrong password.

The UI therefore should be designed to react appropriately for the expected situations, for example give a second and a third attempt. A logical design would therefore be to consider a login failure as one of the possible output of the business logic that was invoked.

Exceptions should be used to handle unexpected situation. For example if the connection to the server is lost, or there's no mor memory. In this case it is quite normal to catch the exception in the vm and try to recover from the error (or limit the damage). Only if this silent recovery fails, should the exception be thrown further to let the Ui take its own recovery steps.

Related Topic