|
- using System;
- using TechbloxModdingAPI.Events;
-
- namespace TechbloxModdingAPI.Utility
- {
- public static class ExceptionUtil
- {
- /// <summary>
- /// Invokes an event with a null-check.
- /// </summary>
- /// <param name="handler">The event to emit, can be null</param>
- /// <param name="sender">Event sender</param>
- /// <param name="args">Event arguments</param>
- /// <typeparam name="T">Type of the event arguments</typeparam>
- public static void InvokeEvent<T>(EventHandler<T> handler, object sender, T args)
- {
- handler?.Invoke(sender, args);
- }
-
- /// <summary>
- /// Wraps the event handler in a try-catch block to avoid propagating exceptions.
- /// </summary>
- /// <param name="handler">The handler to wrap (not null)</param>
- /// <typeparam name="T">Type of the event arguments</typeparam>
- /// <returns>The wrapped handler</returns>
- public static EventHandler<T> WrapHandler<T>(EventHandler<T> handler)
- {
- return (sender, e) =>
- {
- try
- {
- handler(sender, e);
- }
- catch (Exception e1)
- {
- EventRuntimeException wrappedException =
- new EventRuntimeException($"EventHandler with arg type {typeof(T).Name} threw an exception", e1);
- Logging.LogWarning(wrappedException.ToString());
- }
- };
- }
- }
- }
|