rimworld-blax-laws/Source/BlaxLaws/HookGuard.cs

51 lines
1.7 KiB
C#
Raw Normal View History

using System;
namespace BlaxLaws
{
/// <summary>
/// Every Harmony hook catches its own exceptions, so the vanilla method and every other mod's patch
/// always run (design: "Rules every feature follows"). The pattern, in every prefix, postfix and
/// finalizer body:
///
/// try { ... }
/// catch (Exception e) { HookGuard.Fail("hook C, Thing.Ingested", e); }
///
/// Hot hooks write the try/catch themselves; Run allocates a closure per call and is for cold paths
/// only (startup, UI, a sweep). A finalizer always returns void: one that returns an Exception makes
/// Harmony "throw ex" and cuts every other mod's stack trace. A prefix that must not skip vanilla
/// returns void too; a bool prefix returns true from its catch.
/// </summary>
public static class HookGuard
{
/// <summary>Logs the failure once per game under this key and swallows it.</summary>
public static void Fail(string where, Exception e) => LawsLog.Once(where, e);
/// <summary>Runs the body; a throw is logged once and swallowed.</summary>
public static void Run(string where, Action body)
{
try
{
body();
}
catch (Exception e)
{
Fail(where, e);
}
}
/// <summary>Runs the body and returns its value; a throw is logged once and gives the fallback.</summary>
public static T Run<T>(string where, Func<T> body, T fallback)
{
try
{
return body();
}
catch (Exception e)
{
Fail(where, e);
return fallback;
}
}
}
}