Derrick Moeller
Derrick Moeller

Reputation: 4950

WCF Service Falling Through if Statement in catch(Exception ex)

I have a WCF Service, in one of my methods I am attempting to throw an explicit FaultException. This throw is being caught by my catch statement, my intention was to check if the exception is of my explicit type and if so rethrow. The debugger shows this is happening successfully but also throws the new FaultException found after the else. It is the generic FaultException that gets sent to my client. I cannot explain this behavior?

try
{
    using (var db = new DataContext())
    {
        var obj = GetSomeObject(objectId, db);

        if (!obj.Conditional)
            throw new FaultException<ValidateStatusFault>(new ValidateStatusFault { Details = "Object '" + obj.Id + "' has not been some condition.", Issue = "Object '" + obj.Id + "' cannot be validated." });

        // Additional checks.
    }
}
catch (Exception ex)
{
    if (ex is FaultException<ValidateStatusFault>)
        throw; // I reach this breakpoint successfully.
    else
        throw new FaultException(ex.Message); // I also reach this breakpoint?
}

Upvotes: 1

Views: 244

Answers (2)

Tun
Tun

Reputation: 912

unfortunately, 'if statements' in catch block is not working. You have to use like below.

Every single throw statements will be thrown regardless of any if statements.

try {
    tryStatements
}
catch(FaultException<ValidateStatusFault> faultException){ 
    catchStatements
}
catch(Exception ex)
{
  throw new FaultException(ex.Message); 
}
finally {
    finallyStatements
}

Upvotes: 1

user799329
user799329

Reputation: 49

You don't need to do this check explicitly. you can have 2 different exceptions catch and the filtering will be done for you.

try
{
}
catch (FaultException<ValidateStatusFault> faultException)
{
        throw; // I reach this breakpoint successfully.

}
catch(Exception ex)
{
  throw new FaultException(ex.Message); 
}

Upvotes: 0

Related Questions