I am making some code changes for a restful API service, in particular making some notification events completely async, so that a response can be returned without the caller needing to wait for the notification to complete.
To clarify, I am putting a wrapper around existing methods, which previously would have fallen into a catch from the caller, to be run as Fire and Forget tasks. Therefore any exceptions that may be raised by that task will become unhandled.
Also, to clarify, exceptions should be rare, and it doesn't really matter if they happen; these are secondary to the purpose of the API, and if we do get any unhandled exceptions, it's not a big issue that the notification didn't occur. However, I want to be sure that it doesn't affect the overall health of the API in a negative way.
Consider this example:
// this is an example of the application before my change
public class MyService
{
public int MyMethod()
{
try
{
// do stuff
// perform secondary notification
NotificationManager nm = new NotificationManager();
nm.DoNotification();
}
catch (Exception ex)
{
// log exception
}
return 1;
}
}
public class NotificationManager()
{
public void DoNotification()
{
// perform notification
}
}
In this example, the response is forced to wait for the notification event to complete. And if there is an unhandled exception in the DoNotification() method, it will be caught by the catch in the MyMethod() method.
Now, consider if I change the code to something like this:
// this is an example of the application after my change
public class MyService
{
public int MyMethod()
{
try
{
// do stuff
// perform secondary notification
NotificationManager nm = new NotificationManager();
Task.Run(() =>
{
nm.DoNotification();
});
}
catch (Exception ex)
{
// log exception
}
return 1;
}
}
public class NotificationManager()
{
public void DoNotification()
{
// perform notification
}
}
Obviously, if there is an unhandled exception in the DoNotification() method, it will no longer be caught since it has been threaded off.
Just to confirm what I said earlier, I don't particularly care about handling the exception if one is raised, since it is secondary action. However, what I do care about is if it has a negative consequence on the health of the application since in the past we have had code where unhandled exceptions have brought down the entire API. Obviously, in a Production environment, that would be really bad.
So, my question is, what would happen with an unhandled exception in the example above? Would it:
- Be swallowed up by framework, with no one having any knowledge of it occurring? (I would be OK with that), or
- Cause the entire API to crash? (I would not be OK with that)
Many thanks