using System;
using GamecraftModdingAPI.Events;

namespace GamecraftModdingAPI.Utility
{
    public static class ExceptionUtil
    {
        /// <summary>
        /// Invokes an event in a try-catch block to avoid propagating exceptions.
        /// </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)
        {
            try
            {
                handler?.Invoke(sender, args);
            }
            catch (Exception e)
            {
                EventRuntimeException wrappedException =
                    new EventRuntimeException($"EventHandler with arg type {typeof(T).Name} threw an exception", e);
                Logging.LogWarning(wrappedException.ToString());
            }
        }
    }
}