Skip to content

Commit

Permalink
feat(minecraft-extras): Allow platforms to override ComponentMessageT…
Browse files Browse the repository at this point in the history
…hrowable conversions (#87)

Allow platforms to override ComponentMessageThrowable conversions

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 authored Aug 4, 2024
1 parent 34bef65 commit de1762d
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 de1762d

Please sign in to comment.