Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bool (return Type) to handle exceptions or pass exception to client?

I am trying to find out the best way of handling exceptions, I have a number of layers to my application and started to use a return type of BOOL i.e. if it fails then return False and if it succeeds return True..

This works great in methods like SaveMyRecord(somerecord); as i am passing in values and don't require anything returned so i can use the return type of bool to indicate if it succeeds or not.

But then it got me thinking that things like GetMyRecord() actually returns type of IQueryable hence i can't use a bool to tell me if it failed or not.

The thing is i am handle alot of my errors where they happen with try and catch and hence don't want the client to receive an exception.

Maybe there is a better way, i then got thinking about using OUT parameters BUT this means i need to change the signature of all methods and add aditional params..

Maybe i should be passing the exception back to the CLIENT and handling it there?

Is there some standards or any docs to adivse best practices?

like image 445
mark smith Avatar asked Sep 19 '09 12:09

mark smith


2 Answers

Bubble up the exception to the CLIENT and handle it there. Definitely pass it in full detail all the way up. Most best practices almost entirely agree on this, always finally handle on the perimeter, in this case the CLIENT, though in other cases that could be a web service.

Only catch if you want to log it, add more info to it or try and recover from a particular exception. In each case you will will either throw a new exception with the original as the inner or simply 'throw' the original as is, and as pointed in comments don't 'throw ex'

This question is a near duplicate and you'd find lots of existing very well answered questions on SO. I answered a similar one only yesterday

like image 167
dove Avatar answered Oct 22 '22 02:10

dove


You should start reading Design Guidelines for Exceptions

Then, depending on your scenario, you should take other considerations into account such as Exception Shielding.

For instance: If you are using web services (ASMX or WCF) as a back-end, you may want to take a look at Improving Web Services Security and read the parts concerning exception handling.

like image 24
Alfred Myers Avatar answered Oct 22 '22 02:10

Alfred Myers