WCF - Faults / Exceptions versus Messages

前端 未结 3 2030
轻奢々
轻奢々 2020-12-07 17:12

We\'re currently having a debate whether it\'s better to throw faults over a WCF channel, versus passing a message indicating the status or the response from a service.

相关标签:
3条回答
  • 2020-12-07 17:14

    This however carries overhead as throwing exceptions in .NET can be quite costly.

    You're serializing and de-serializing objects to XML and sending them over a slow network.. the overhead from throwing an exception is negligable compared to that.

    I usually stick to throwing exceptions, since they clearly communicate something went wrong and all webservice toolkits have a good way of handling them.

    In your sample I would throw an UnauthorizedAccessException with the message "Account Locked".

    Clarification: The .NET wcf services translate exceptions to FaultContracts by default, but you can change this behaviour. MSDN:Specifying and Handling Faults in Contracts and Services

    0 讨论(0)
  • 2020-12-07 17:17

    If you think about calling the service like calling any other method, it may help put things into perspective. Imagine if every method you called returned a status, and you it was up to you to check whether it was true or false. It would get quite tedious.

    result = CallMethod();
    if (!result.Success) handleError();
    
    result = CallAnotherMethod();
    if (!result.Success) handleError();
    
    result = NotAgain();
    if (!result.Success) handleError();
    

    This is one of the strong points of a structured error handling system, is that you can separate your actual logic from your error handling. You don't have to keep checking, you know it was a success if no exception was thrown.

    try 
    {
        CallMethod();
        CallAnotherMethod();
        NotAgain();
    }
    catch (Exception e)
    {
        handleError();
    }
    

    At the same time, by returning a result you're putting more responsibility on the client. You may well know to check for errors in the result object, but John Doe comes in and just starts calling away to your service, oblivious that anything is wrong because an exception is not thrown. This is another great strength of exceptions is that they give us a good slap in the face when something is wrong and needs to be taken care of.

    0 讨论(0)
  • 2020-12-07 17:27

    I would seriously consider using the FaultContract and FaultException objects to get around this. This will allow you to pass meaningful error messages back to the client, but only when a fault condition occurs.

    Unfortunately, I'm in a training course at the moment, so can't write up a full answer, but as luck would have it I'm learning about exception management in WCF applications. I'll post back tonight with more information. (Sorry it's a feeble answer)

    0 讨论(0)
提交回复
热议问题