runtime: Allow ignoring unhandled exceptions in UnhandledException event handler
Background and Motivation
Scenarios like designers or REPLs that host user provided code are not able to handle unhandled exceptions thrown by the user provided code. Unhandled exceptions on finalizer thread, threadpool threads or user created threads will take down the whole process. This is not desirable experience for these type of scenarios.
The discussion that lead to this proposal is in https://github.com/dotnet/runtime/issues/39587
Proposed API
Allow ignoring unhandled exceptions on threads created by the runtime from managed UnhandledException handler:
namespace System
{
public class UnhandledExceptionEventArgs
{
// Existing property. Always true in .NET Core today. The behavior will be changed to:
+ // - `false` for exceptions that can be ignored (ie thread was created by the runtime)
+ // - `true` for exceptions that cannot be ignored (ie foreign thread or other situations when it is not reasonably possible to continue execution)
// This behavior is close to .NET Framework 1.x behavior of this property.
public bool IsTerminating { get; }
+ // The default value is false. The event handlers can set it to true to make
+ // runtime ignore the exception. It has effect only when IsTerminating is false.
+ // The documentation will come with usual disclaimer for bad consequences of ignoring exceptions
+ public bool Ignore { get; set; }
}
}
Usage Examples
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
if (DesignMode && !e.IsTerminating)
{
DisplayException(e.ExceptionObject);
e.Ignore = true;
}
};
Alternative Designs
Unmanaged hosting API that enables this behavior. (CoreCLR has poorly documented and poorly tested configuration option for this today.)
Similar prior art:
UnobservedTaskExceptionEventArgs.Observed+UnobservedTaskExceptionEventArgs.SetObservedCancelEventArgs.Cancel
Risks
This API can be abused to ignore unhandled exceptions in scenarios where it is not warranted.
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 14
- Comments: 89 (80 by maintainers)
It seems this issue is also blocking an important plugin for Unreal Engine ( https://github.com/nxrighthere/UnrealCLR/issues/33 ) while this was moved to the Future milestone, I’d like to push this to be taken into consideration for .NET 6 or even .NET 7. It’s kinda discouraging to see it stuck in that milestone that only god-knows-when will be done.
Considering the positive impact that project is making in the UE community as a whole, I think it’s important to look at.
Excluding the UE topic, this issue is pretty valid to me in some apps I’ve developed in the past, too. Haven’t needed it, but it would’ve been a good addition to some workarounds I’ve had to implement.
We need this functionality.
I would create a new small header file for this. It can live in https://github.com/dotnet/runtime/tree/main/src/native/public. I would not worry about shipping it - just tell people to copy it over from the repo if they need it.
(We have header files for debugger, profiler or hosting. Each of these are handled differently, there is not much consistency.)
NativeLibrary.Load+NativeLibrary.GetExport. It does not work with static linkinghttps://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.objectivec.objectivecmarshal.initialize?view=net-8.0 is recently added API with similar shape. It has the function pointers in the signature.
I think either way, we can say that once
UnhandledExceptionHandlerreturns true, this is no longer an unhandled case soCurrentDomain.UnhandledExceptionis not called, regardless of the runtime.I’d prefer ExceptionServices. This can be seen as orthogonal to
CurrentDomain.UnhandledException, thus does not need to live near it.I think I might prefer a single shot delegate (the
DllImportResolverstyle). Solves the problem with multiple handlers. Or at least moves it to the user, who still can build something pluggable or flow this into an event.But I’d like to hear from the likely users.
Yeah, let’s try to get this done for .NET 9.
I don’t like Ignorable \ Ignore. Whoever handle the unhandled exception may not necessarily ignore it, maybe they will choose to not just take down the current process, but the whole OS as well. Or they could choose to ignore the unhandled exception. Point is, we only know that someone handled it. We don’t know how they handled it. Ignoring it is just one way of handling it.
Better names: bool CanBeHandled; bool Handled;
Video
The combined proposal is at https://github.com/dotnet/runtime/issues/101560
@jkotas @AaronRobinsonMSFT - huge thanks for helping with this!!
LGTM
Nit: The example has
GetFatalErrorHandleron the managed side, but it does not show it on the unmanaged side.I have applied all the suggestions. I think this is ready to be put in one proposal (together with managed handler part) and send to API review.
The latest iteration that should capture all the suggestions so far. Let me know if I missed/misunderstood something or there are some additional thoughts.
The API definition:
Managed API to set up the handler
The shape of the FatalErrorHandler, if implemented in c++ (the default calling convention for the given platform is used)
With
FatalErrorHandlerResultandFatalErrorInfodefined in “TBD.h” as:Typical use:
Setting up the handler for the app (C# code in the actual app):
The handler. (c++ in
myCustomCrashHandler.dll)If the fail-fast is originating as Environment.FailFast, I do not have concerns about collecting the stacktrace upfront like we do that today.
I have concerns about computing the stacktrace automatically for failfasts that are e.g. crashes in the middle of GC. We do print the managed stacktrace to console for these today, but it is not clear whether it is a good idea. We have seen situations where it caused secondary crashes and made the original crash undiagnosable.
I think the managed stacktrace needs to be optional and only computed if the handler wants it given that computing it is a very complex operation. I do not have a strong opinion about how it should be formatted.
This may change as we make progress on cDAC.
Makes sense. I did notice that unlike hosting, the strings go in a different direction (from runtime to the handler).
By
char16_t- do you mean on both Windows and Unix? Any thoughts about encoding?I would call it
int32_t hresultthen (to matchException.HResultthat is the same kind of error code).What kind of
error_codeis this?EXCEPTION_POINTERS is bundle of EXCEPTION_RECORD and CONTEXT. It corresponds to siginfo_t* and ucontext_t*. We may want to split it into two fields like this:
We should call it
FatalErrorData(orFatalErrorInfo) to matchSetFatalErrorHandler.I agree, but then the declarations become muddled and we end up requiring people to define complex structures. If we instead make the data structures simple the declarations are easy to copy/paste and users can simply cast in the implementation if needed. One could imagine something akin to the following:
So the signature could be:
Now we need to settle on how
ExceptionDatalooks likeOn Windows CoreCLR, exceptions escaping from reverse PInvokes are converted to Windows SEH exceptions. Exceptions escaping from reverse PInvokes are treated as unhandled exceptions everywhere else.
To handle unhandled exception in reverse PInvoke, we would have to return something to the unmanaged code that called the reverse PInvoke. What would that be? Returning random values and hope for the best does not sound like a good plan.
For the semantics of unhandled exception handler I think we can follow the model of imaginary
in places where the above will not lead to process termination regardless of what
handler()returns.false.Any other interesting scenario or a corner case?
The first one wins. It is how AssemblyResolve and similar events work today. One example from many: https://github.com/dotnet/runtime/blob/aee49579769188d0ff7cf3ca872d2126e5bb3c70/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs#L811-L821
Still not a great name.
Proposed API
Allow ignoring unhandled exceptions on threads created by the runtime from new managed UnhandledExceptionThrowing handler:
The exception will be reported in existing UnhandledException event, whether it’s ignored or not.
UnhandledExceptionEventArgs.IsTerminatingwill be false if the exception was ignorable and ignored.Usage Examples