Tracking Event Processor - Retry Execption originating from Event Handlers - axon

I am trying to configure an ErrorHandler for a TrackingEventProcessor so that any exception in my #EventHandler annotated method will be retried.
Currently using Axon Framework 4 and looking how to achieve this.

I'd recommend to set the PropagatingErrorHandler as the ListenerInvocationErrorHandler in this case.
Know that there are two error handling levels within a given Event Processor, namely:
The ListenerInvocationErrorHandler, catching the exceptions thrown from within your #EventHandler annotated methods. This defaults to a LoggingErrorHandler instance, which logs the exception.
The ErrorHandler, catching the transaction exceptions of the given EventProcessor. This defaults to a PropagatingErrorHandler, which rethrows the exceptions.
The TrackingEventProcessor (TEP) EventProcessor implementation is the one which will retry events with a certain (unconfigurable) back-off, if the configured ErrorHandler throws an exception.
If you want to retry on every exception (which might be a debatable approach anyhow), you'd thus want to enter the retry scheme of the TEP. To achieve this, you simply should configure the ListenerInvocationErrorHandler to also be a PropagatingErrorHandler. I'd recommending reading the Reference Guide on the matter too, to get a better idea of how to configure this.

Related

Listener-level error handler vs Container-level error handler in Spring Kafka

With my team, we are trying to set up an error handling policy common to several microservices (for the majority of cases). My team and I are struggling to understand the difference between a listener-level error handler and a container-level error handler. What are the real implications behind this choice? Is it only the fact that the container error handler does not have access to the message?
The KafkaListenerErrorHandler allows a more fine grained exception handling, we can use on the content of the exception to define if it is retryable or not.
In the error handler containers it seems more complicated, before it was possible to provide a custom classifier but not anymore, we can only pass a classification map.
In the past we used to use the SeekToCurrentErrorHandler (now DefaultErrorHandler), which was recommended in the documentation. I saw another StackOverflow thread related to this topic but I can't quite make the connection with our questions. The documentation doesn't seem to address the implications of this choice.
Thank you very much.
The main use case for the listener-level error handler is for request/reply processing; it allows the error handler to send some other result to the sender to indicate the request wasn't processed. As you say, it also provides access to the spring-messaging converted Message<?> (possibly with a converted payload); e.g. for logging; it can re-throw the exception to invoke the container EH.
Regarding classification, that change was to allow classifications to be added and removed dynamically. If you prefer to have the old behavior (allowing a custom classifier) to be restored, please open an issue on GitHub.

Should I catch all my exceptions in the global.asax?

If I am just logging exception details in my web app, do I really need to put in exception handling logic for each tier? Why not just let them all bubble up the stack trace to the global.asax and log them there?
I would suggest against using any exception handling logic in any layer of your application unless:
The exception is not a fatal one, meaning that there is some action you can take to recover, or
The application should continue functioning and the exception should be "ignored." An example: when checking out at an online retailer you are sent a receipt via email. If that fails - but the other order processing stuff succeeds - the user should not be shown an error page. Here, we want the workflow to continue even though there is an exception. Most exceptions do not fall into this category.
Of course, exceptions - whether they are fatal or not or should be "ignored" or not - need to be logged and developers notified. This is best handled through an event handler for the Application.Error event. Yes, this can be done in Global.asax, but I think it's cleaner to use an HTTP Module-based approach, either Health Monitoring or ELMAH.
I've written an article on this topic that I'd like to recommend to you - Exception Handling Advice for ASP.NET Web Applications. Here is the article in summary:
My advice for handling exceptions in an ASP.NET application can be boiled down to the following guidelines:
(a) Create and use a meaningful custom error page.
(b) In general, do not catch exceptions. Let them bubble up to the ASP.NET runtime. Some cases where catching an exception makes sense include:
When there is a plausible way to recover from the exception by performing some alternative logic,
When a peripheral part of the application's workflow throws and exception and that exception should not derail the entire application, and
When you need to include additional information with the exception by throwing a new exception that has the original exception as its inner exception.
(c) Log all exceptions to some persistent store and use email (or some other medium) to notify developers when an exception occurs in production. Consider using ELMAH or ASP.NET's built-in Health Monitoring system to facilitate this process.
Exceptions should bubble up to whatever layer can handle them in a meaningful way, being aware of the Single Responsibility principle. For instance, your data layer should not be invested in logging.
The Application.Error event is a good place for catch-all error handling: that is, unexpected and/or fatal errors that require no special treatment beyond logging/alerting and redirecting to an error page.
If your web app makes use of the Microsoft AJAX extensions and partial postbacks, you'll need to handle exceptions in at least two places:
Global.asax
Your ScriptManager's OnAsyncPostBackError handler
For further information on OnAsyncPostBackError, check out:
http://msforge.net/blogs/janko/archive/2008/02/13/handling-exceptions-in-asp-net-ajax.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.onasyncpostbackerror.aspx
I say that on global try to catch the error that you miss on the logic steps of your program and redirect them on an "error page", or a "not found page".
All other errors not necessary show the error on the user, and not need to send it to an error page.
For example, in page with 2 or more, different modules, if the one throw an error, just hide it, and show the rest. Similar try to catch errors when they happens and handle them the best non visual way to the user if this is possible, log them and correct them later.
Now this error that happens only on one module, you can see it on your log and correct it, but until you do that, user see something on your page and not a full error page.
Usually what I do is do a try...catch in the code, but instead of logging on the catch what I do is pass it on with a message stating where the error came from, etc. Then I use Elmah to catch all of the errors and log them.
That way you only have to deal with the logging in one area and satisfy the Single Responsiblity Principle, but you have more information available for debugging purposes. It can also be helpful when you get that data error that only seems to occur with 1 out of 500 users.

How to return errors to view from controller not tied to a specific model property

Curious what the best practice is for returning errors to a view from a controller where the error isn't really a validation error, but more like "user not found" or "service timeout" type of errors. (in ASP.NET MVC2 framework)
I've been adding them to the ModelState's model errors, but that doesn't seem appropriate. (although easy to implement and maintain)
Example - A user tries to log in, and their credentials do not match a known user.
I believe you need to be slightly more clear with regards to what youre calling an error.
Exceptions (timed out, database error, etc.) should be handled using specific exception handlers (not least because you often don't want to show the error message to the end user).
In this scenario, look at overloading the OnException() method on the controller. (or having all your controllers inherit from a common ControllerBase which has that method overriden to avoid repetition)
You may also want to check the value of filterContext.HttpContext.IsCustomErrorEnabled when handling exceptions to determine whether to expose detailed exception information or to obfuscate it.
Remember that exceptions should be for exceptional circumstances - "normal" operation should never result in an exception
The other type of error you're mentioning is more like "Unable to process request due to business rules / invalid input" (or similar) in which case, adding error messages to the ViewModel seems appropriate. They may not be direct validation errors but they are most likely as a result of the user input
I've just researched this, and I think that for network-related errors and so on, which are bound to happen, it's OK to use TempData (but don't put the Exception inside but the exception message only, for security reasons).
http://forums.asp.net/p/1460169/3353779.aspx

ASP.NET logging Events in DB

Can ASP.NET's System.web.Management be used for logging events like user logins, password changes and access to certain resources? Should system.Web.Management be used for logging of errors and health monitoring instead?
I want to log events without re-inventing the whole thing. I know ELMAH is used for errors; can it be used for logging events too?
From the article ELMAH - Error Logging Modules And Handlers on the now defunct DoNetSlackers:
Error signaling is exposed via the ErrorSignal class, which provides a single overloaded method called Raise. Simply put, exceptions raised via the ErrorSignal class are not thrown, therefore they don't bubble up, but instead are only sent out to ELMAH, as well as to whomever subscribes to the Raise event of the ErrorSignal class.
The code snippet below shows how to obtain an instance of the ErrorSignal class, which is unique per application and can be retrieved simply with the static FromCurrentContext method, and then use it to signal an exception.
ErrorSignal.FromCurrentContext().Raise(new NotSupportedException());
The difference between signaling and throwing an exception is that in the first case no one will ever know about the error except ELMAH.
Further Reading:
How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

Exception Handling in .net web apps

I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill.
I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen.
So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered?
Sorry for the vague the question but I really want to close the book on this once and for all.
Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block
Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling.
To get you started I recommend read following articles:
Exception Handling on MSDN
Exception Management in .NET on MSDN
Exception Handling Best Practices in .NET on CodeProject
ASP.NET specific articles:
User Friendly ASP.NET Exception Handling
Global Exception Handling with
ASP.NET
Exception handling in C# and ASP
.Net
The golden rule with exception handling is:
"Only catch what you know how to handle"
I've seen too many try-catch blocks where the catch does nothing but rethrow the exception. This adds no value. Just because you call a method that has the potential to throw an exception doesn't mean you have to deal with the possible exception in the calling code. It is often perfectly acceptable to let exceptions propagate up the call stack to some other code that does know what to do.
In some cases, it is valid to let exceptions propagate all the way up to the user interface layer then catch and display the message to the user. It might be that no code is best-placed to know how to handle the situation and the user must decide the course of action.
I recommend you start by adding a good error page that catches all exceptions and prints a slightly less unfriendly message to the user. Be sure to log all details available of the exception and revise that. Let the user know that you have done this, and give him a link back to a page that will (probably) work.
Now, use that log to detect where special exception handling should be put in place. Remember that there is no use in catching an exception unless you plan to do something with it. If you have the above page in place, there is no use in catching database exceptions individually on all db operations, unless you have some specific way to recover at that specific point.
Remember: The only thing worse than not catching exceptions, is catching them and not doing nothing. This will only hide the real problems.
Might be more about exception handling in general than ASP.NET speific but:
Try to catch exceptions as close to
the cause as possible so that you
can record (log) as much information
about the exception as possible.
Include some form of catch all, last
resort exception handler at the
entry points to your program. In
ASP.NET this could be the
Application level error handler.
If you don't know how to "correctly" handle an exception let it bubble up to the catch all handler where you can treat it as an "unexpected" exception.
Use the Try***** methods in .NET
for things like accessing a
Dictionary. This helps avoid major
performance problems (exception
handling is relatively slow) if you
throw multiple exceptions in say a
loop.
Don't use exception handling to
control normal logic of your
program, e.g. exiting from a loop via
a throw statement.
Start off with a global exception handler such as http://code.google.com/p/elmah/.
Then the question comes down to what kind of application are you writting and what kind of user experience do you need to provide. The more rich the user experience the better exception handling you'll want to provide.
As an example consider a photo hosting site which has disk quotas, filesize limits, image dimension limits, etc. For each error you could simply return "An error has occured. Please try again". Or you could get into detailed error handling:
"Your file is to large. Maximum
filesizes is 5mb."
"Your image is is
to large. Maximum dimensions are
1200x1200."
"Your album is full.
Maximum storage capacity is 1gb".
"There was an error with your
upload. Our hampsters are unhappy.
Please come back later."
etc. etc.
There is no one size fits all for exception handling.
Well at the very basic level you should be handling the HttpApplication.Error event in the Global.asax file. This should log any exception that occurs to a single place so you can review the stack trace of the exception.
Apart from this basic level you should ideally be handling exceptions where you know you can recover from them - for example if you expect a file might be locked then handling the IOException and reporting the error back to the user would be a good idea.

Resources