Custom Exceptions and Angular Error Handling

This blog covers a straight forward example of handling errors via custom exceptions from the server and displaying the exception message on the client using an angular service.

Server:

Step 1:

Create Custom Exceptions

namespace Business.Exceptions
{
  public class ProblematicWebServiceException : Exception
  {
   public ProblematicWebServiceException()
   : base()
   {

   }
   public ProblematicWebServiceException(string message)
   : base(message)
   {

   }
   public ProblematicWebServiceException(string message, Exception innerException)
   : base(message, innerException)
   {

   }
  }
}

Step 2:

Wrap code that has the potential to fail in try/catch blocks and throw custom exception with a helpful error message. This is probably going to be in the Business layer depending on the architecture of the application.

try
{
   problematicService.GetSomeStuff();
}
catch (Exception)
{
   throw new Business.Exceptions.ProblematicWebServiceException("The Problematic Web Service is temporarily down.");
}

 

Step 3:

Catch exceptions as they bubble up to the application’s service layer and return appropriate Http Status Code(Service Unavailable 503 in this case):

catch (Business.Exceptions.ProblematicWebServiceException ex)
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new StringContent(ex.Message)
                };
                throw new HttpResponseException(response);
            }

Client:

Step 4:

Create Shared Service to handle errors:


angular.module('Shared.Services.SharedDataService', [])
    .service('sharedData', ['$rootScope', '$cookies', '$http', '$location',  function ($rootScope, $cookies, $http, $location) {
   var handleFault = function (context,error) {

   if (error.status === 503 && error.data) {
                errorMessage = error.data;
            }

   return {message:errorMessage,details:errorDetails}
        };
}

Step 5:

Handle error using $resource’s error callback to display the error message to the user:

MyResource.get({ 'id': customerId },
        function (response) {
            $location.path('/customerDetails/' + customerId);
        },
        function (error) {
            $scope.isError = true;
            $scope.errorMessage = sharedData.handleFault("gettingProblematicServiceCustomer", error).message;
        });