views:

395

answers:

1

I have a webservice written in C#. When errors occur on the server, I would like to inform the user client side. This works fine by throwing exceptions server side, which is then sent to my error handler client side.

However, I would like to, when I throw the exception, to set a property describing how serious I think the error is at this point. Thus I can decide client side how to display the error:

WebService.Method(some_value, handle_response, handle_error);

function handle_response (response) {
    //Do something...
}

function handle_error (error) {
    if(error.level === 'Critical') {
        //Show critical message.
    } else if(error.level === 'Warning') {
        //Show warning message.
    } else 
        ...
    }
}

My solution so far has been to create a custom exception inheriting from System.Exception. My webservice returns with a JSON formatted result.

My problem is how to get my property through to the client side JSON response?

+3  A: 

web service:

     public Response zzz()
        {
          Response result;
           try
        {
         ...
        }
        catch(MyException)
        {
          result.HasError = true;
          result.Error.Level = Normal;
          result.Error.Message = "It's OK.";
        }
        catch(Exception)
        {
result.HasError = true;
          result.Error.Level = Critical;
          result.Error.Message = "!!!!";
        }
        }

then check Response.HasError

igor
I have previously used something similar, but this time I would like the error handling to go through the ASP.NET webservice error handling - see my edit.
Chau
Are you using WCF or classical (old style) webservices? WCF has one place to handle all exceptions (without try/catch in every method).
igor
I guess, it is the best choice (way) to use "Shielding Exception" pattern, not to display inner exception (real exception) to a client. This is a security issue. The server should process exception and return user-friendly message to a client
igor
Response result;..catch(Exception ex){ ProcessException(result, ex);}
igor
@Igor: I am using the classical .amsx web service. Your suggestion to use the "Shielding Exception" pattern seems like a good idea to me and I will do that. But still, it does not answer my question though. But thanks a lot for your comments!
Chau
Hello,In this case you can handle SoapException exception. :(. It is painful. I wanted to avoid that in my answer. You can catch and find out one of variants of parsing of SoapException (if your client is .net application) or use that Response.Error structure (if your client is html page + javascript). I don't know what client you are using. Any way it will be SoapException with something strange :) text in it. If all methods throw the same exception then you can parse this SoapException inner text well.
igor