A stable modding interface between Techblox and mods https://mod.exmods.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.5KB

  1. using System;
  2. using TechbloxModdingAPI.Events;
  3. namespace TechbloxModdingAPI.Utility
  4. {
  5. public static class ExceptionUtil
  6. {
  7. /// <summary>
  8. /// Invokes an event with a null-check.
  9. /// </summary>
  10. /// <param name="handler">The event to emit, can be null</param>
  11. /// <param name="sender">Event sender</param>
  12. /// <param name="args">Event arguments</param>
  13. /// <typeparam name="T">Type of the event arguments</typeparam>
  14. public static void InvokeEvent<T>(EventHandler<T> handler, object sender, T args)
  15. {
  16. handler?.Invoke(sender, args);
  17. }
  18. /// <summary>
  19. /// Wraps the event handler in a try-catch block to avoid propagating exceptions.
  20. /// </summary>
  21. /// <param name="handler">The handler to wrap (not null)</param>
  22. /// <typeparam name="T">Type of the event arguments</typeparam>
  23. /// <returns>The wrapped handler</returns>
  24. public static EventHandler<T> WrapHandler<T>(EventHandler<T> handler)
  25. {
  26. return (sender, e) =>
  27. {
  28. try
  29. {
  30. handler(sender, e);
  31. }
  32. catch (Exception e1)
  33. {
  34. EventRuntimeException wrappedException =
  35. new EventRuntimeException($"EventHandler with arg type {typeof(T).Name} threw an exception", e1);
  36. Logging.LogWarning(wrappedException.ToString());
  37. }
  38. };
  39. }
  40. }
  41. }