Skip to content

Commit

Permalink
Allow platforms to override ComponentMessageThrowable conversions
Browse files Browse the repository at this point in the history
We don't use ServiceLoader as that would require other workarounds on NeoForge
(the target for this change), due to non-'GAMELIBRARY's not being able to discover
game-aware service implementations.
  • Loading branch information
jpenilla committed Aug 2, 2024
1 parent 34bef65 commit 2070dcb
Showing 1 changed file with 44 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,9 @@ private static <C> Component getMessage(final ComponentCaptionFormatter<C> forma
if (throwable instanceof ParserException) {
return ((ParserException) throwable).formatCaption(formatter);
}
final Component msg = ComponentMessageThrowable.getOrConvertMessage(throwable);
final Component msg = ComponentMessageThrowable.getOrConvertMessage(
ComponentMessageThrowableConverterHolder.instance.maybeConvert(throwable)
);
return msg == null ? NULL : msg;
}

Expand Down Expand Up @@ -472,4 +474,45 @@ public interface Decorator<C> {
@NonNull Component message
);
}

/**
* Converts Throwables to ComponentMessageThrowables when possible.
*/
@API(status = API.Status.INTERNAL)
@FunctionalInterface
public interface ComponentMessageThrowableConverter {
/**
* Converts a Throwable to a ComponentMessageThrowable if possible.
*
* @param thr throwable
* @return possibly converted throwable
*/
Throwable maybeConvert(Throwable thr);
}

/**
* Default implementation and holder for {@link ComponentMessageThrowableConverter}.
*/
@API(status = API.Status.INTERNAL)
public static final class ComponentMessageThrowableConverterHolder implements ComponentMessageThrowableConverter {
private static ComponentMessageThrowableConverter instance = new ComponentMessageThrowableConverterHolder();

/**
* Replaces the converter. Mainly useful for platforms that need custom logic to transform vanilla CommandSyntaxExceptions
* into an Adventure representation.
*
* @param converter converter
*/
public static void converter(final ComponentMessageThrowableConverter converter) {
instance = Objects.requireNonNull(converter, "converter");
}

private ComponentMessageThrowableConverterHolder() {
}

@Override
public Throwable maybeConvert(final Throwable thr) {
return thr;
}
}
}

0 comments on commit 2070dcb

Please sign in to comment.