Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

If you are creating new strongly typed exceptions to throw you need something to handle them.  The translation of exceptions to the JSON object is handled by implementations of ServicesExceptionHandling.IExceptionResponseHandler.  You do not need to implement this interface directly.  If the default JSON object format is acceptable for you, you should instead inherit ServicesExceptionHanding.AbstractExceptionResponseHandler.  This abstract class implements most of the behavior described in this document.  There is one abstract method that must be implemented to determine the correct HttpStatusCode for the response.  The abstract class will take care of blanking out the message property on the JSON object based on the HttpStatusCode.  You should also implement ServicesExceptionHandling.ICustomExceptionResponseHandler.  Implementing this interfaces allows your implementations to go first when handling exceptions, ensuring your configurations take priority over stock behavior.  

Do I have to register a new handler for every exception type I plan on throwing?

...

First, name your handler class with the convention {exceptionType}ResponseHandler.  So if your exception class is CustomerException your handler class would be named CustomerExceptionResponseHandler.  This is the default pattern AbstractExceptionRepsonseHandler uses in its CanHandle method.  Second, register your handler as a named instance of IExceptionResponseHandler ICustomExceptionResponseHandler through through the DI containerThis ensures your exception handler will execute before any stock handlers.  For example:  

Code Block
languagec#
public class Installer : ISecondaryUnityInstaller
{
    public void Install(IUnityContainer container)
    {
        container.RegisterType<IExceptionResponseHandlerRegisterType<ICustomExceptionResponseHandler, CustomerExceptionResponseHandler>(typeof(CustomerExceptionResponseHandler).FullName);
    }
}

...

Any exceptions that do not have an explicit handler will be processed by this one.