StructureMap 2.6.1.0 Assembly scanning issue - assemblies

I am trying to use StructureMap to scan at runtime for assemblies that contain an implementation of the Registry class, but I'm running into a problem.
If a dll contains a Registry class, but also contains a reference to a dll that isn't present at runtime (say a Rhino.Mocks dll that isn't required at runtime), StructureMap will throw a StructureMapConfiguration exception resulting from an Assembly.GetExportedTypes() call.
Is there a way to avoid this behaviour in StructureMap?
ObjectFactory.Initialize(x =>
{
x.Scan(s =>
{
s.AssembliesFromApplicationBaseDirectory();
s.LookForRegistries();
});
});

Through reflector i found that with the call to graph.Log.AssertFailures() any exceptions that may have occurred during assembly scanning (that includes the ones that are thrown during assembly.GetExportedTypes() which are the ones that you are referring to) are thrown as one big exception. I havent found anything indicating that this behavior can be somehow switched off. What I found out though is that if you catch the exception, the scanning actually succeeds with any assemblies that it managed to scan. StructureMap cannot actually do anything about exceptions being thrown when calling GetExportedTypes() (which is a framework method) except continue to the next assembly. If you dont mind 'losing' some assemblies just catch the exception and move on.
public void Configure(Action configure)
{
lock (this)
{
ConfigurationExpression expression = new ConfigurationExpression();
configure(expression);
PluginGraph graph = expression.BuildGraph();
graph.Log.AssertFailures();
this._interceptorLibrary.ImportFrom(graph.InterceptorLibrary);
this._pipelineGraph.ImportFrom(graph);
}
}

Related

Generic CommandExecutionException handling in axon framework

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.

Asp.net unhandled exception in timer callback crashes w3wp and error not logged

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.

JVMVRFY012: VerifyError for JSTL Tags - Foreach & Set tags

IBM WAS: 8.5.5 Version
On JSP pages have & tags, I receive below error
Error 500: java.lang.Exception: java.lang.VerifyError: JVMVRFY012
stack shape inconsistent; class=com/ibm/_jsp/_desktop,
method=_jspx_meth_c_set_0(Ljavax/servlet/jsp/PageContext;)Z, pc=73;
Type Mismatch, argument 1 in signature
org/apache/jasper/el/ELContextWrapper.:(Ljavax/el/ELContext;Ljavax/el/FunctionMapper;)V
does not match Exception Details:
Location:
com/ibm/_jsp/_desktop._jspx_meth_c_set_0(Ljavax/servlet/jsp/PageContext;)Z
#73: JBinvokespecial Reason: Type
'org/apache/jasper/runtime/ProtectedFunctionMapper' (current frame,
stack[8]) is not assignable to 'javax/el/FunctionMapper'
Current Frame: bci: #73 flags: { } locals: { 'com/ibm/_jsp/_desktop',
'javax/servlet/jsp/PageContext', 'javax/servlet/jsp/JspWriter',
'org/apache/taglibs/standard/tag/rt/core/SetTag' } stack: {
'org/apache/taglibs/standard/tag/rt/core/SetTag', 'uninitialized',
'uninitialized', 'java/lang/String', 'javax/el/ExpressionFactory',
'uninitialized', 'uninitialized', 'javax/el/ELContext',
'org/apache/jasper/runtime/ProtectedFunctionMapper' } Stackmap Table:
append_frame(#128,Object[#127],Object[#231],integer)
On reading https://www.ibm.com/support/pages/ibm-java-linux-howto-resolving-javalangverifyerror-jvmvrfy012-stack-shape-inconsistent, understand that the reason could be
code is compiled against a different library than the one being used at runtime
a class tries to extend a class declared as final
a method tries to override a super method that is declared as final
a wrong argument is passed to a method
It does look to be #4 - but the same code works in Tomcat and does not work in IBM WAS and am unsure why WAS is passing an incorrect argument. Any suggestions on how we can resolve this issue?
You may want to explore Servlet/JSP version compatibility.
WAS: 8.5.5 reference
Servlet 3.0
JSP 2.2
If you happen to be using Spring Boot:
2.2.x and 2.1.x require Servlet 3.1+
2.0.x supports Servlet 3.0
This looks like a cross-linkage between the javax.el library in your application and the version packaged in the server. When using PARENT_LAST, any Java EE APIs you include in the application are loaded twice, once from the server and once from the application (because the application loader doesn't delegate that load to its parents). Depending on the other classes/packages in play, you can have an instance in which a class ends up directly referencing one instance of the class and indirectly (through some other reference) referencing the other instance, and the JVM will throw a VerifyError in that scenario.
The easiest answer: If you are not 200% sure you NEED the version of the javax.el classes in the app, remove them, and this specific error should be impossible. If you are definitely dependent on that version, then it becomes trickier, as it might require adding additional stuff to the application (to avoid picking stuff up from the server), or it may be that this specific library simply can't be safely overridden with PARENT_LAST loading. That analysis would require a deeper look at the error stack and possibly a dive into detail trace of the class loading.

Application_Start timeout?

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.

Qt/C++ event loop exception handling

I am having an application heavily based on QT and on a lot of third party libs. These happen to throw some exceptions in several cases.
In a native Qt App this causes the application to abort or terminate. Often the main data model is still intact as I am keeping it in pure Qt with no external data.
So I am thinking that I could also just recover by telling the user that there has occurred an error in this an that process and he should save now or even decide to continue working on the main model.
Currently the program just silently exits without even telling a story.
Sometimes it's really hard to catch all exception. If one exception accidently slips through, the following helps a lot. Inherit from QApplication and override the notify() function in the following way
bool MyApplication::notify(
QObject * receiver,
QEvent * event )
{
try
{
return QApplication::notify(receiver, event);
}
catch(...)
{
assert( !"Oops. Forgot to catch exception?" );
// may be handle exception here ...
}
return false;
}
Then replace the QApplication in your main() function by your custom class. All events and slots are issued through this function, so that all exceptions can be caught and your application becomes stable.
As stated in the Qt documentation here, Qt is currently not fully exception safe. The "Recovering from exceptions" section on that page describes the only thing which you can do in a Qt application when an exception is thrown - clean up and exit the app.
Given that you are using third party libraries which do throw exceptions, you need to catch these at the boundary between the external library and the Qt code, and handle them there - as stated in Caleb's comment. If the error must be propagated into the Qt application, this must be done either by returning an error code (if possible), or by posting an event.

Resources