I have a fairly simple axon application that Im trying to apply some generic "catch all" exception handling logic to.
If I have a command that goes into an aggregate that throws some kind of exception e.g.
class UserAggregate {
//...
#CommandHandler()
public void on(CreateUserCommand cmd) {
Validate.notNull(cmd.getEmail(), "Email cannot be null");
//other processing
}
}
Then when I invoke this command from the Rest Controller, then the exception is far away from what I would expect
org.axonframework.commandhandling.CommandExecutionException: Email cannot be null
at org.axonframework.axonserver.connector.ErrorCode.lambda$static$10(ErrorCode.java:88)
at org.axonframework.axonserver.connector.ErrorCode.convert(ErrorCode.java:182)
at org.axonframework.axonserver.connector.command.CommandSerializer.deserialize(CommandSerializer.java:157)
at org.axonframework.axonserver.connector.command.AxonServerCommandBus$1.onNext(AxonServerCommandBus.java:313)
at org.axonframework.axonserver.connector.command.AxonServerCommandBus$1.onNext(AxonServerCommandBus.java:306)
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onMessage(ClientCalls.java:429)
at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1MessagesAvailable.runInternal(ClientCallImpl.java:596)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1MessagesAvailable.runInContext(ClientCallImpl.java:581)
Granted the message is useful, however, this is not always a given. This can be mitigated when implementing an ExceptionHandler like so
#ExceptionHandler
public void handle(Exception exception) {
log.info("Caught Exception - {}", exception.getMessage(), exception);
}
This now gives me a stack trace pinpointing where the issue actually came from, however, this comes at the cost of having to write such an ExceptionHandler everywhere I would like to invoke this command.
Is there a more generic way to log these exceptions without having to impose the ExceptionHandler on every class issueing commands?
I would point you to the code-samples repo, where it shows a way of handling it using a MessageHandlerInterceptor.
Quoting from the repo itself:
One of the most common ways to indicate that a logical error has occurred and that Command handling failed is to throw an exception from a Command handler. However, if the exception is directly serialized there is no guarantee that the command sending side can properly deserialize the exception in question.
That is why by default Axon Framework will wrap any exception thrown inside a Command handler into a CommandExecutionException.
In short, you are going to define a MessageHandlerInterceptor responsible to try-catch the command execution logic. There you would have your centralized way of handling the CommandExecutionException.
Related
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
public void Trans_Rollback()
{
trans.Rollback();
con.Close();
}
Looks like you disposed 'trans' or 'con' variable (or both) before calling 'TransRollback()'.
If you're using NHibernate, take a look to the querying part. If you use using statement with any of these variables you need to call your rollback method before statement parenthesis closes, since it means disposing object using were used with.
If that's not your case - provide more information, maybe at least framework you're using for accessing database. And context you calling your rollback method from.
I am experiencing some randomly happening unhandled exception causing w3wp to crash. I want to trace the cause of that exception. I already have a global Application_Error handler override in my MvcApplication class, so the crash must be caused by some out-of-http-context exception. In order to replicate the problem I genereate one myself in a timer callback, and try to trace it. Simplified code like
public static class MonitorTimers
{
public static Timer _taskMonitorTimer = new Timer(state: null, dueTime: 1000, period: 1000, callback: (state) =>
{
throw new Exception("Ouch! Me dead.");
});
}
In my local development environment (iisexpress launched by VS2017) and test environment (IIS 8.5), when the app starts and then crashes, the following can be seen in event viewer:
The most useful Event 1325 and 1026 sourced from ASP.NET and .NET Runtime shows the stack trace - just the thing I need.
My problem is, in my production machine (also IIS 8.5) I can't find the useful event 1325. Only a crash report, bearing no more information than I know. So I don't know what caused the error. I could surround my timer callback with try...catch block but the error could well be caused by something else (unmanaged libraries, error in static class initialization) then I still can't trace.
So suggestions on why event 1325 is missing or some tools that can show the log and analyse the stack trace is greatly appreciated. Thank you.
So, in your case you generate Exception diring Loading of application domain.
When CLR load application domain it firstly init static fields. So, if your code has problem with static fields, then exception will throw until it specifies Application_Error handler.
One more point, Is your application take a lot of memory? There are 2 cases when application can not write logs and execute code in catch block: StackOverflowException and OutOfMemoryException. Can you check is it has some memory leaks or infinite recursion?
One more point: set in visual studion setting to break when any exception throwed.
One more point: It is better to move your initialization logic from static constructors to ApplicationStart or something like this. You can do it temporary, for catch the bag and then move it to previous state.
I have an async Task with a method signature defined like this:
public async Task<bool> HandleFooAsync()
When executing this task in an async way and discarding the results, exceptions happening in this task do not show up in our logs.
_ = _slackResponseService.HandleFooAsync();
When I await the execution of the task I see the error in our logs
var result = await _slackResponseService.HandleFooAsync();
Is this expected behaviour? Is there a way to achieve a solution in between: "do not wait for the result, but log errors nevertheless.." ? We invested hours debugging our logging setup, just to learn that our logging setup is correct, but discard means in dotnet that everything is discarded - even logs. Which is a quite a new perspective for us, coming from a Python background.
Our logging setup follows the default logging setup for dotnet core 3 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
Yes, it is an expected behavior. Call in that way can be considered like an anti-pattern. You can read about it C# Async Antipatterns
You need something which is called as "Fire and forget". One of its implementation can be find in repo AsyncAwaitBestPractices (nuget available too).
A Task in .net and netcore is meant to be awaited. If it is not awaited, the scope might be destroyed before the async method has finished.
If you want to run tasks in the background and not wait for a result you can use BackgroundService in .netcore or a third party such as Hangfire which supports fire and forget jobs out of the box
https://medium.com/#daniel.sagita/backgroundservice-for-a-long-running-work-3debe8f8d25b
https://www.hangfire.io/
One solution is to subscribe to the TaskScheduler.UnobservedTaskException event. It is not ideal because the event is raised when the faulted Task is garbage collected, which may happen long after the actual fault.
Another solution could be to use an extension method every time a task is fired and forgotten. Like this:
_slackResponseService.HandleFooAsync().FireAndForget();
Here is a basic implementation of the FireAndForget method:
public async static void FireAndForget(this Task task)
{
try
{
await task;
}
catch (Exception ex)
{
// log the exception here
}
}
I am new to the EJB Projects. And am trying to understand the usage of #Transactional annotation at top of my EJB methods. I have searched for the content and there is no clear explanation on this. Can anyone explain clearly about this.
#Transactional comes from the Spring world, but Oracle finally included it in Java EE 7 specification (docs). Previously, you could only annotate EJBs with #TransactionAttribute annotation, and similar is now possible for CDIs as well, with #Transactional. What's the purpose of these annotations? It is a signal to the application server that certain class or method is transactional, indicating also how it is gonna behave in certain conditions, e.g. what if it's called inside a transaction etc.
An example:
#Transactional(Transactional.TxType.MANDATORY)
public void methodThatRequiresTransaction()
{
..
}
The method above will throw an exception if it is not called within a transaction.
#Transactional(Transactional.TxType.REQUIRES_NEW)
public void methodThatWillStartNewTransaction()
{
..
}
Interceptor will begin a new JTA transaction for the execution of this method, regardless whether it is called inside a running transaction or not. However, if it is called inside a transaction, that transaction will be suspended during the execution of this method.
See also:
TransactionalTxType
I have one piece of code that gets run on Application_Start for seeding demo data into my database, but I'm getting an exception saying:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
While trying to enumerate one of my entities DB.ENTITY.SELECT(x => x.Id == value);
I've checked my code and I'm not disposing my context before my operation, Below is an outline of my current implementation:
protected void Application_Start()
{
SeedDemoData();
}
public static void SeedDemoData()
{
using(var context = new DBContext())
{
// my code is run here.
}
}
So I was wondering if Application_Start is timing out and forcing my db context to close its connection before it completes.
Note: I know the code because I'm using it on a different place and it is unit tested and over there it works without any issues.
Any ideas of what could be the issue here? or what I'm missing?
After a few hours investigating the issue I found that it is being caused by the data context having pending changes on a different thread. Our current implementation for database upgrades/migrations runs on a parallel thread to our App_Start method so I noticed that the entity I'm trying enumerate is being altered at the same time, even that they are being run on different data contexts EF is noticing that something is wrong while accessing the entity and returning an incorrect error message saying that the datacontext is disposed while the actual exception is that the entity state is modified but not saved.
The actual solution for my issue was to move all the seed data functions to the database upgrades/migrations scripts so that the entities are only modified on one place at the time.