Search code examples
c#silverlightexceptionwcf-ria-services

Proper handling of DomainOperationException


In my Silverlight application I want properly handle different server errors. I created handler for DomainOperationException but there I want to get more specific information about root cause of a problem and provide more clear messages for user.


Possible ways to do this:

  • OperationStatus gives me some advantages, but still mostly all errors that are connected to server have OperationStatus.ServerError whether it is DB or IIS issue;
  • Exception also has ErrorCode property, but I don't know where to get list of possible error codes that will be suitable with RIA;

NOTE: Even without setting ErrorCode by myself it has value 500 when issue with DB connection occurs on server side. That's why I'm hoping that RIA is doing all dirty work, and I will avoid doing this redundant effort.


Questions:

  1. What is the best way to properly handle DomainOperationException?
  2. Where to get possible error codes?

Solution

  • The ErrorCode is a user-defined value. MSDN states that it

    Gets or sets the custom error code for this exception. The error code can be any user-defined value.

    Probably there are more elegant solutions but what I ended up doing is to create a Portable Class Library (but you can use a .shared classes too) where I defined an enum with my error codes. I referenced that project in the server-side and the client side projects.

    I then overrode the DomainService's OnError-method and did something like this:

     protected override void OnError(DomainServiceErrorInfo errorInfo)
     {
         if (errorInfo.Error is UnauthorizedAccessException)
         {
             errorInfo.Error = new DomainException("Denied access.",(int)MyErrorCodesEnum.Permission_Unauthorized, errorInfo.Error);
         }
     }
    

    (Looking at this code it makes me want to create kind of an associative list of exception types and enumerator values so I can drop the if but you get the idea)

    On client-side I do:

    switch ((MyErrorCodesEnum)(s.Error as DomainException).ErrorCode)
    {
        case MyErrorCodesEnum.Permission_Unauthorized:
            //do something
            s.MarkErrorAsHandled();
            break;
    }