I am using entity framework for my project with MVC as front end and I have implemented unit of work pattern with repository pattern.
I have service layer on top of repositories to handle business.
My question is where to handle exceptions?
Is it good idea to let pass through all exceptions to presentation layer and handle it in the controller or do I need to handle it in the bottom layers?
Well, the general idea is not to let UI handle all exceptions, nor that makes much sense. Lets say you have a data layer implemented with ADO.NET. The general pattern here is to handle SqlExceptions in data layer, and then wrap the SqlException in a more meaningfull DatabaseLayerException that upper layers should handle - and you follow this pattern all the way to the top, so you can have something like InfrastructureException, ApplicationException etc...
On the very top, you catch all ApplicationExceptions that went unhandled (and you make all your exceptions inherit this one for polymorphism), and you catch all unhandled Exceptions as a special case not likely to happen, and try to recover from it.
I also suggest use of logging, either manually or with AOP - you will find plenty of resources online (perhaps Log4Net ?).
I think in any exception handeling strategy you have these options:
to recover from the exception if possible (for instance server is down, wait a while and try again)
Ignore the exception because it's not serious enough or whatever other reasons.
Bubble it upwards. Multiple strategies exist here, such as just a throw; or throw new Exception("message", InnerException); to name a few.
Lastly there are the global options to log the exception to some log format, or to send an email, etc. I don't include this in the above three options, because this is global to all the above three options.
So having said that I think that at each layer in your application described above you have to ask your self in which of the above three ways can you handle the exception. If you can not recover from it or ignore it, then you should bubble it upwards to a friendly error page where you do final cleaning up and presentation of the exception.
Related
So, the question is in the title.
The only one thought that comes in mind why we need to introduce custom Exception class is to pass additional info with exception raising.
Any additional reasons?
There are several reasons why you may want to create custom exceptions:
Add custom logic to an exception, to simplify the interaction with the exception itself. ActiveRecord::RecordInvalid is an example: the message is built from the actual record errors, and a reference to the record itself is stored in the exception.
Differentiate errors to improve error handling. Having different error types allows you to specifically rescue only certain types of errors, and not all the errors. You can also have different rescue blocks depending on the error type.
Re-raising typed errors. This is very important for libraries that internally relies on other libraries. A good practice of software composition is that library A uses B internally, whatever error B raises should be wrapped into an A error to make sure that the users of A don't have to deal with B directly.
In general, providing custom errors enhances the error handling experience. A good resource to learn more about errors is Avdi's book Exceptional Ruby. Highly recommended.
To avoid the Pokemon exception handling (Gotta' catch them all) anti-pattern it is better to raise your own exception types.
When using a library for example you should get meaningful error types - for example AuthorizationError or TimeOutError - it lets programmers deal with exceptions by type instead of matching the error message or adding a clunky system of numeric codes which does not really belong in an object oriented language.
I am developing a RESTful service and I want to return 400 for all unsupported URLs.
My question is when should I choose method 1 over method 2 and vice-versa..
//method 1
public ActionResult Index()
{
//The url is unsupported
throw new HttpException(400, "Bad Request");
}
This one seems to be better?
//method 2
public ActionResult Index()
{
//The url is unsupported
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
The second seems better as it doesn't involve exception throwing which comes at a micro-cost compared to the first example.
Being in a DevOps team, we are all in the mind-set where throwing more hardware at something to get a slightly better result is always a good cause. So I'm intentionally ignoring the micro-cost of firing a .NET exception.
If you're leveraging a telemetry framework like ApplicationInsights then just returning the status code gives you nothing more than a "failed request". It doesn't give you any useful information that allows you to either compile or get any information on the "why" of the failed request.
Telemetry platforms expect and want you to throw, because error telemetry is usually around .NET exceptions, so if you're not throwing you're creating a problem for operations.
I actually landed here, because I'm in the process of writing a Roslyn analyser and CodeFix for a project where folks love to write try{} catch { return BadRequest("put_the_reason_here"); } and neither DevOps or the Dev teams see nothing useful in the system telemetry in ApplicationInsights.
In my view you need to consider first if a request is made to the unsupported URLs. Then do you think of it is an exceptional situation or you expect that to happen? If you think of it as an exceptional situation then create and throw an exception (option 1). If you are expecting that you will receive many requests on the unsupported URL then treat it as a function of your application and use method 2.
That's said you will need to think about your clients' again if you are expecting too many requests on the unsupported URLs. In general I would prefer to throw an exception as I don't expect to receive too many requests on the unsupported URLs, and if it does happen then I would like to log it as an exception and investigate the reason.
Although this question is a bit old I figured I'd give my input since I came across this.
Errors are values. This goes for an HttpException (when unthrown) as well as an HttpStatusCodeResult. Thrown exceptions, however, create new code paths that are hidden away from your coworkers that may be one execution context higher up than yours and have to be given documentation that these code paths will be passed to them without notice. Values, however, tell you everything you need to know through their type. You can use their type in the expected execution path to tell whether an error has occured as well as find associated information with that error and log it.
I sometimes use (lightly extended) Exception's without throwing them to the next execution context to extract the useful debug information that David Rodriguez mentioned. There's never an excuse to be handing thrown exceptions to execution contexts above you that aren't actually exceptional, and this only really applies to things that are actually outside of your code's ability to handle (StackOverflowException, other fatal system exceptions, etc).
In a networked application, such as whatever MVC service you're running, the performance penalty from throwing exceptions is meaningless. The semantics and effects on maintainability, are not.
Network errors are values, and you should handle them like so.
you would throw an exception in code locations that cannot return an actionResult, such as in a controller constructor.
Can anyone please explain difference between below two approaches.
Logging in controller's OnException event:
try
{
//code
}
catch
{
//rollback trasanctions
throw;
}
Or, logging in catch block:
try
{
//code
}
catch
{
//logging here
//rollback trasactions
throw;
}
The Controller's OnException method is used when an unhandled exception occurs in the processing of the request. It is indicates what functionality should happen if an unexpected exception occurs. You should really only use this as a safeguard in the event that you messed up or the system failed in an unexpected, fatal way.
If you are executing some piece of code that you expect to throw a specific exception, wrap it in try block, and handle the specific exception accordingly. This defensive approach will help you debug issues as soon as they happen, rather than wait for them to bubble up to a point where you don't know the cause.
Think about it, if you have multiple action methods and only one OnException method per controller, then you have a much more complex issue to handle, because any of the action methods or filters could have thrown the error. However, if you catch an exception called by a specific service call then you already know exactly what caused the unexpected behavior, and it will be much easier to address accordingly.
Read this for greater understanding: Eric Lippert has an excellent article in which he breaks down the different categories of exceptions that we encounter and offers best practices for addressing them. It is available at http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx . In case you don't know who Eric Lippert is, he is very smart and you should listen to him if you code in C#. His main points are:
Don’t catch fatal exceptions; nothing you can do about them anyway, and trying to generally makes it worse.
Fix your code so that it never triggers a boneheaded exception – an "index out of range" exception should never happen in production code.
Avoid vexing exceptions whenever possible by calling the “Try” versions of those vexing methods that throw in non-exceptional circumstances. If you cannot avoid calling a vexing method, catch its vexing exceptions.
Always handle exceptions that indicate unexpected exogenous conditions; generally it is not worthwhile or practical to anticipate every possible failure. Just try the operation and be prepared to handle the exception.
Update
Just realized I didn't explicitly address the "logging" question. It probably makes most sense to avoid handling your fatal/exogenous errors in a controller scope, because you will end up duplicating your logic, often. This behavior is better handled in a global action filter.
This codeproject article Exception Handling in ASP.NET MVC explains how to override the default HandleErrorAttribute and leverage an ErrorController so that it can be applied globally.
In addition, the following 5-part blog series gives an in depth analysis of the different options you have for error handling in MVC applications: http://perspectivespace.com/error-handling-in-aspnet-mvc-3-index-of-posts
It's not my intent to engage in a debate over validation in DDD, where the code belongs, etc. but to focus on one possible approach and how to address localization issues. I have the following behavior (method) on one of my domain objects (entities) which exemplifies the scenario:
public void ClockIn()
{
if (WasTerminated)
{
throw new InvalidOperationException("Cannot clock-in a terminated employee.");
}
ClockedInAt = DateTime.Now;
:
}
As you can see, when the ClockIn method is called, the method checks the state of the object to ensure that the Employee has not been terminated. If the Employee was terminated, we throw an exception consistent with the "don't let your entities enter an invalid state" approach.
My problem is that I need to localize the exception message. This is typically done (in this application) using an application service (ILocalizationService) that is imported using MEF in classes that require access to its methods. However, as with any DI framework, dependencies are only injected/imported if the object was instantiated by the container. This is typically not the case with DDD.
Furthermore, everything I've learned about DDD says that our domain objects should not have dependencies and those concerns should be handled external from the domain object. If that is the case, how can I go about localizing messages such as the one shown above?
This is not a novel requirement as a great many business applications require globalization/localization. I'd appreciate some recommendations how to make this work and still be consistent with the goals of a DDD.
UPDATE
I failed to originally point out that our localization is all database driven, so we do have a Localization Service (via the injectable ILocalizationService interface). Therefore, using the static Resources class Visual Studio provides as part of the project is NOT a viable option.
ANOTHER UPDATE
Perhaps it would move the discussion along to state that the app is a RESTful service app. Therefore, the client could be a simple web browser. As such, I cannot code with any expectation that the caller can perform any kind of localization, code mapping, etc. When an exception occurs (and in this approach, attempting to put the domain object into an invalid state is an exception), an exception is thrown and the appropriate HTTP status code returned along with the exception message which should be localized to the caller's culture (Accept-Language).
Not sure how helpful this response is to you, but localization is really a front-end concern. Localizing exceptions messages as per your example is not common practice, as end users shouldn't see technical details such as those described in exception messages (and whoever will be troubleshooting your exceptions probably has a sufficient level English even if it is not their native language).
Of course if necessary you can always handle exceptions and present a localized, user-friendly message to your users in your front-end. But keeping it as a font-end concern should simplify your architecture.
As Clafou said, you shouldn't use exceptions for passing messages to the UI in any way.
If you still insist in doing this, one option is to throw an error code instead of the message
throw new InvalidOperationException("ERROR_TERMINATED_EMPLOYEE_CLOCKIN");
and then, when it happens, do whatever you need to do with the exception (log, look up localization, whatever).
If localisation is important part of the domain/application you should make it a first class citizen and inject wherever it belongs. I am not sure what you mean with "DDD says that our domain objects should not have dependencies" - please explain.
You are correct for trying to avoid adding internal dependencies to your domain model objects.
A better solution would be to handle the action inside of a service method such as:
public class EmployeeServiceImpl implements EmployeeService {
public void ClockEmployeeIn(Employee employee) throws InvalidOperationException {
if (employee.isTerminated()) {
// Localize using a resource lookup code..
throw new InvalidOperationException("Error_Clockin_Employee_Terminated");
}
employee.setClockedInAt(DateTime.Now);
}
}
You can then inject the service using your DI framework at the point where you will be making the clockin call and use the service to insulate your domain objects from changes to business logic.
I have an Autofac DI Container and use constructor injection to inject configuration settings into my SampleClass. The Configuration Manager class is created as a singleInstance so the same single instance is used.
public ConfigurationManager()
{
// Load the configuration settings
GetConfigurationSettings();
}
public SampleClass(IConfigurationManager configurationManager)
{
_configurationManager = configurationManager;
}
I am loading the configuration settings from a App.config file in the constructor of the configuration Manager. My problem is i am also validating the configuration settings and if they are not in the App.config file a exception is thrown, which causes the program to crash. Which means I cant handle the exception and return a response.
I am doing this the wrong way? Is there a better way to load the configuration settings Or is there a way to handle the exception being thrown.
Edit
ConfigurationManager configurationManager = new ConfigurationManager();
configurationManager.GetConfigurationSettings();
//Try catch around for the exception thrown if config settings fail
//Register the instance above with autofac
builder.Register(configurationManager()).As<IConfigurationManager>().SingleInstance();
//Old way of registering the configurationManager
builder.Register(c => new ConfigurationManager()).As<IConfigurationManager>().SingleInstance();
You are doing absolutely the right thing. Why? You are preventing the system from starting when the application isn't configured correctly. The last thing you want to happen is that the system actually starts and fails later on. Fail fast! However, make sure that this exception doesn't get lost. You could make sure the exception gets logged.
One note though. The general advice is to do as little as possible in the constructor of a type. Just store the incoming dependencies in instance variables and that's it. This way construction of a type is really fast and can never really fail. In general, building up the dependency graph should be quick and should not fail. In your case this would not really be a problem, since you want the system to fail as soon as possible (during start-up). Still, for the sake of complying to general advice, you might want to extract this validation process outside of that type. So instead of calling GetConfigurationSettings inside that constructor, call it directly from the composition root (the code where you wire up the container) and supply the valid configuration settings object to the constructor of the ConfigurationManager. This way you -not only- make the ConfigurationManager simpler, but you can let the system fail even faster.
The core issue is that you are mixing the composition and execution of your object graph by doing some execution during composition. In the DI style, constructors should be as simple as possible. When your class is asked to perform some meaningful work, such as when the GetConfigurationSettings method is called, that is your signal to begin in earnest.
The main benefit of structuring things in this way is that it makes everything more predictable. Errors during composition really are composition errors, and errors during execution really are execution errors.
The timing of work is also more predictable. I realize that application configuration doesn't really change during runtime, but let's say you had a class which reads a file. If you read it in the constructor during composition, the file's contents may change by the time you use that data during execution. However, if you read the file during execution, you are guaranteed to avoid the timing issues that inevitably arise with that form of caching.
If caching is a part of your algorithm, as I imagine it is for GetConfigurationSettings, it still makes sense to implement that as part of execution rather than composition. The cached values may not have the same lifetime as the ConfigurationManager instance. Even if they do, encoding that into the constructor leaves you only one option, where as an execution-time cache offers far more flexibility and it solves your exception ambuguity issue.
I would not call throwing exceptions at composition-time a good practice. It is so because composition might have a fairly complex and indirect execution logic making reasonable exception handling virtually impossible. I doubt you could invent anything better than awful
try
{
var someComponent = context.Resolve<SampleClass>();
}
catch
{
// Yeah, just stub all exceptions cause you have no idea of what to expect
}
I'd recommend redesigning your classes in a way that their constructors do not throw exceptions unless they do really really need to do that (e.g. if they are absolutely useless with a null-valued constructor parameter). Then you'll need some methods that initialize your app, handle errors and possibly interact with user to do that.