We are Refactoring (and of-course redesigning) our Services in layered design.
We have Service operations layer (BLL), Network abstraction layer -> (deals with network proxy), Data abstraction layer.
But we are a bit baffled about our exception handling strategy.
We don't want to expose too much information from BLL to outside world. (from other layers to bll is fine)
We don't want to clutter the code with try catch stacks
We don't want to mess the exception handling code(like logging, emailing etc) in catch blocks
Could someone post some code samples or literature pointers which we can use to design our simple exception handling framework?
We don't want to expose too much information from BLL to outside world.
(from other layers to bll is fine)
It's BLL itself that defines what's exposed. Make sure You show what's intended to be seen.
We don't want to clutter the code with try catch stacks
Then don't. Exceptions are exceptions. Don't control flow using them. Let them blow up.
We don't want to mess the exception handling code(like logging, emailing etc) in catch blocks
If Your logic does not rely on exception handling (which it should not) and Your code guards itself (this one is important, Your application should ALWAYS blow up on invalid state instead of working further. otherwise - it's hard to understand what causes what), then it's more than enough with wrapping whole app with only 1 error handler that dumps stack trace where necessary.
E.g. - in .net, You can use subscribing to appdomain unhandled exception event for that.
I personally use ELMAH for my web application - few lines in app.config and I have nice error log, stored in sqlite, easily accessable from web app itself. That's about all error handling I got.
Eric Lippert has a wonderful article on how to handle exceptions. I think it would be useful.
Exception handing can be as complex as you want but the good way is to use some global definition. For example by aspects which you can build with any AOP framework - part of most IoC containers like Unity, Windsor Castle, Spring.NET. Separate category of AOP frameworks is PostSharp which adds aspects on compile time insted of runtime.
Also you can check Enterprise Library 5.0 and its Exception handling application block which allows you to do policy based exception handling out of the box.
Related
I have a C# console project where I have separated out the business logic from the UI. The business logic calls an API, retrieves JSON data, and then updates a database with the data. The UI handles the display of the results and also loops through a queue to process records with the business logic.
My question is how to properly handle exceptions thrown by the business logic. The UI project currently handles exceptions that bubble up but I want to give as detailed an error message as possible. For example, sometimes the API fails to authorize or may be down and I want to log that specific exception. The problem is the UI project does not know anything about HttpRequestException without me adding a reference to the System.Net.Http library, which creates a dependency I don't want.
What is the "best practice" for handling exceptions in a project other than where they are generated?
If you want to pass detailed messages to the UI project without explicitly referencing System.Net.Http, consider catching these HTTP exceptions in the business logic, wrapping them in an exception type you define in that library, and re-throwing the new exception. Then your UI library only needs to know about the business logic library, which it's already referencing, and the business logic can provide the most informative message possible for things it can't properly recover from.
I'd say the best practice is to not handle them. You don't know what those exceptions are, so how can you "handle" them?
Either trust the Message property of these exceptions and display them to the users, or just tell the users "sorry, something bad happened".
Keep in mind that your users will need to read the detailed messages and decide what to do about them. Quite likely they'll either ignore the messages or else call someone to ask what to do about them. Make sure you log enough information to answer the call. Sometimes, you're just better off displaying a message that says, "Please call someone who can figure out what went wrong".
I am working on re-writing a business layer for one of the apps in company. For now, the business layer will interface directly with the web client. But in the future, it will be encapsulated with service interfaces and will be consumed by the same web client.
My question is that when a validation exception or other exceptions occur in the business layer, is it okay to throw custom exceptions or would it be better to use custom objects that represent errors ... like ValidationError, etc? Is it more expensive to throw an exception vs returning an object?
The most popular thought on this today is to throw the errors towards the application layer. I guess the idea is so that the interpretation of what went wrong and telling the user is more clear there than way down in the guts of the applications.
Some people catch errors everywhere and then throw them as they go, this leaves a trail of traceable documentation for the developer.
One other interesting point, if the developer makes all the error messages contain unique identifiers, then they are easily able to debug because they can pinpoint the code just by looking for that number.
Throwing an exception is way more expensive than returning an object. Exceptions should be used only for unexpected situations. Errors in validation of user input is not unexpected and should not result in an exception being thrown.
I'm developing in a code block has been written by a previous developer, he did not like handling exceptions at all!
I wonder if I could found any guideline about exception handling in general.
For example: Assuming there is a method responsible for executing a query in database, if it fails in the connection then should it throws the same exception to the caller? or it should just handle it and log it and returns false (means failed).
I know that the question seems to be subjective, I just want any resources, guideline or standard for exception handling.
Regards.
If you ask 10 developers, you're likely to get 10 different answers. A general rule of thumb I live by is that exception handling should be standardized and not repeated in every single method. I try to strive for exceptions to be handled once per layer in a consistent manner.
So in a standard 3 layer architecture (presentation, business, data), you would have a standard exception handling mechanism at each layer, and all three of those mechanisms would behind the scenes call the same logging/notification/etc.
Here is a link to Microsoft's Best Practices.
Exception handling is a 'concern' as in Separation of Concerns and as such it should not be sprinkled around your application and mixed in with your core business logic. It's an area that will likely evolve at a different pace than your business logic.
For example you mentioned opening a database connection. You might start off by logging the exception, but later on you might determine that it should auto retry on timeout, or send an alert or maybe it would be appropriate to implement the Circuit Breaker Pattern.
Adhering to the single responsibility principle and separation of concerns enable you to independently evolve your exception handling behavior. Consider this interface:
public interface IConnectionFactory
{
IConnection Create();
}
If you do not do any exception handling in your base implementation, that allows you use inheritance, the decorator pattern or some facility of your framework to add additional behavior.
public class RetryOnTimeoutConnectionFactory { ... }
public class CircuitBreakerConnectionFactory { ... }
The other thing to consider is context. You mentioned this is web service. Well if you are following REST semantics, you would probably translate your exceptions into HTTP status codes depending on the classification of the exception. If you trap your exceptions at a low level and silently return false then you really handcuff yourself.
I am doing some enhancements to existing code. And now I want to log one message whenever and wherever exception occurs.
I can add that message in catch/finally block but there are hundreds of catch blocks.
Can anyone suggest better approach to have the message logged whenever exceptions occurs at any part of the code in the assembly?
Second take:
A good approach is AOP with Postsharp.
I've used in many projects.
You can define an attribute that inherits from a base one of PostSharp API which permits you to intercept any method call of the one where you place your custom attribute.
If you put that attribute in any method, you'll be able to try/catch absolutely any method body, and, in the end, control exceptions and logging them.
You can achieve the same goal with Castle Dynamic Proxy, but this is a run-time solution, since you can create proxy classes with interceptors and instantiate your classes with a factory. Obviously, this is consuming more resources.
Postsharp performs IL weaving, meaning that your interceptors will be injected in your actual code in compile-time, so, you don't loose run-time performance.
Summarizing, you can create a "LogAttribute" and place it in any method you want to log or do things if an exception happens.
This is an interesting issue when you have legacy code you have to deal with.
If you REALLY do not want to change your catch blocks, then I might suggest a workaround :
One option you got is writing aLoggedExceptionInterfaceor whatever, and implement aLogEventin it, and then audit all of your code scanning for handled exception types and redefening them by adding your interface to them.
For example you would replace IOException by LoggedIOException where the latter inherits the first, implementing the LoggedExceptionInterface on top.
Of course, this might turn out to be heavier than changing catch blocks individually;The choice is yours.
For sure, you've last-chance exception handlers.
ASP.NET has it in the HttpApplication, with the Error event (most of the times in the Global ASAX if you're not using an HTTP Module).
WPF and Silverlight have then in the Application.
And Windows Forms can use the AppDomain.UnhandledException event.
Mika Jacobi is right, this is a bad answer. Sorry for that.
I have an application that has many tiers.
as in, i have...
Presentation Layer (PL) - > contains all the html
My Codes Layer (CL) -> has all my code
Entity Layer (EL) -> has all the container entities
Business Logic Layer (BLL) -> has the necessary business logic
Data Logic Layer (DLL) -> any logic against data
Data Access Layer (DAL) -> one that accesses data from the database
Now i want to provide error handling in my DLL since it is responsible for executing statement like ExecureScalar and all....
And i am confused as to how to go about it...i mean do i catch the error in the DLL and throw it back to the BLL and from there throw it back to my code or what....
can any one please help me how do i implement a clean and easy error handling techinque
help you be really appreciated.
Thank you.
You can look at the MS Enterprise Block for error handling and logging. It is nice in terms of configurability. Alternatively Codelpex (codeplex.com) is the community site for MS technology open source projects. Codeplex also have some error handling libraries.
In my opinion it all depends on the kind of exception and what kind of handling you want to with it.
Some errors need to be presented to the user of course. If your application relies heavily on a database connection and your database server is unreachable you need to 'bubble' (not sure if that is the right term?) your event all the way up to your GUI and let the user know that an error occurred.
But if other errors can be handled by your application itself, you just need to 'bubble' the event up to the layer where you can handle it.
As said, there are loads of libraries which can help you handle and log errors easily and the choice for such a library is completely dependent on your project and what suits your needs.
Handle all Excpetions in DLL only, call generateEmail() for notifying admin and send only user defined error messsage from DLL-->BLL-->web-Page and redirect from here to Custom error pages
.on DLL layer generate Email along all exception info with idictionary custom defined arguments (this is what i use for my arguments)
.try catch only in DLL only
.Don't re throw exception on any layer..bad programming techniques
.send error message from DLL--BLL-->web page
.check if is the errfield !="" response.redirect("errorUserPage.")