Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should web services throw exceptions OR result objects

I'm not sure I'm completely happy that throwing exceptions in web services is a good idea. I wouldnt mind as much if it wasn't for the stack trace. This is not something I wan't.

I have researched around several implementations and there really doesn't seem to be a consensus on this. CampaignMonitor for example does return a Result object, yet others don't.

Architecturally, I'm not sure returning a return object makes sense, surely an exception is an exception, but what I do like about a Return object is that it is a more graceful solution for the end user.

Does anyone have any better solutions?

EDIT

BTW I am using ASMX web services, where turning CustomErrors on is not an option.

like image 757
Ryan Tomlinson Avatar asked Jun 19 '09 17:06

Ryan Tomlinson


3 Answers

Don't let the fact that you're in a web service confuse the issue. That's just an implementation detail.

Use your normal exception handling strategy. Best practice says don't trap exceptions in low level code -- unless you can resolve that exception there and continue normally. Exceptions should be raised to the presentation layer so the user can be informed of the error.

So, as applied to web services -- in general throw exceptions (which results in a SoapFault). This allows the invoking client code to use it's built-in exception handling standard to handle it.

like image 153
Maladon Avatar answered Oct 17 '22 20:10

Maladon


What stack trace are you talking about? Have you tried this?

In both ASMX and WCF services, an uncaught exception will be translated into a SOAP Fault. In both cases, they can be configured to not include any stack trace. In fact, that's the default in WCF.

So, the proper way to return an error like this is through a fault. One way to generate faults is to throw and not handle an exception.

like image 6
John Saunders Avatar answered Oct 17 '22 19:10

John Saunders


one approach is to separate system and business errors. (System error: e.g. malformed request, user-not-authorized, etc.; business error: e.g. method UpdateCars results in an error, the user doesn't own any cars).

In case of a business error, return a response object containing an error description; in case of a system error, throw an exception.

like image 2
azheglov Avatar answered Oct 17 '22 20:10

azheglov