Is it best practice to wrap a web service method/call into a try/catch block?
I don't web service requests tend to be the reason why the .NET desktop applications crash? So I was thinking all calls should be wrapped in try/catch to prevent this.
Good idea?
Also, should it throw an exception or just have an empty catch?
I am assuming you are using WCF, since your question is tagged with it. A good practice in exception handling with WFC is not allowing exceptions to bubble across the wire to your consumer, but throw meaningful FaultExceptions instead.
You should always have a try...catch block in your operation if there is any chance an exception could be generated by it. If you allow the raw excption to bubble, only two scenarios can result: If you have configured your service to allow exception details in faults, you will expose internals of your service opening up yourself for security breaches. Or you don't have this configured in your service and the consumer gets a very generic message that indicates something went wrong, which is not very useful for them or the support team.
What you should do is declare one or more FaultExceptions, depending on what messages you want the user to receive from your operation, decorate them as FaultContracts on your operation declaration. Then you can try...catch specific exceptions and throw specific Faults. You can also have a try...catch that catches exception and throw a very general Fault.
The key here, is not revealing too much information of what is going on with your operation internally - especially stack traces!
The fault is just another data contract, so it is declared in your WSDL. This means that your consumer can catch the fault specifically and can react to faults thrown from your operation as if it was an exception being thrown from their code.
Hope this helps.
Joe.
Yes, you should wrap Web service call in try-catch. DON'T use empty catch as they (mostly) are pure evil. Your catch block should at least log exception. I don't know about your applications logic, but probably some message (like "information from service wasn't fetched because of tech error") should be shown to user.
It's ok, but try to just catch exception types that you can handle.
Avoid catching any "Exception" or, if you do so, log and/or alert the user and/or retry to call the webservice.
If it's a windows forms app I usually wrap the last "Exception" catch in an #if DEBUG block to avoid hiding exceptions while debugging or testing.
#if !DEBUG
catch (Exception ex)
{
// show messagebox, log, etc
}
#endif
this is a case that could result in an exception being thrown, so yes it should be wrapped on a try catch block.
What to do with the exception handler it depends on the program logic...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With