From dd77e4628f1a65f332f0cb81c82a19c0fcfa40c2 Mon Sep 17 00:00:00 2001 From: Vyacheslav <6242627+vkryl@users.noreply.github.com> Date: Wed, 25 Oct 2023 00:52:34 +0600 Subject: [PATCH] Strong typed API for synchronous TDLib method execution in Java interface `Client.execute` in Java interface is now strongly typed: returned TDLib object type depends on the return type defined in the corresponding Function class. When TDLib error is occurred, method now throws `Client.ExecutionError`. This change adds compile-time protection against return type change and allows using this pattern: ``` try { TdApi.SpecificReturnType result = Client.execute(function); // work with strongly typed resultl without casting and type checks } catch (Client.ExecutionError error) { // Handle error } ``` --- example/java/org/drinkless/tdlib/Client.java | 31 ++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/example/java/org/drinkless/tdlib/Client.java b/example/java/org/drinkless/tdlib/Client.java index 2dd324f132e9..55d53566c3fd 100644 --- a/example/java/org/drinkless/tdlib/Client.java +++ b/example/java/org/drinkless/tdlib/Client.java @@ -62,6 +62,24 @@ public interface LogMessageHandler { void onLogMessage(int verbosityLevel, String message); } + /** + * Exception class thrown when TDLib error occurred while performing {@link #execute(TdApi.Function)}. + */ + public static class ExecutionError extends Throwable { + /** + * Original TDLib error occurred when performing one of the synchronous functions. + */ + public final TdApi.Error error; + + /** + * @param error TDLib error occurred while performing {@link #execute(TdApi.Function)}. + */ + ExecutionError (TdApi.Error error) { + super(error.code + ": " + error.message); + this.error = error; + } + } + /** * Sends a request to the TDLib. * @@ -102,8 +120,17 @@ public void send(TdApi.Function query, ResultHandler resultHandler) { * @return request result. * @throws NullPointerException if query is null. */ - public static TdApi.Object execute(TdApi.Function query) { - return nativeClientExecute(query); + public static T execute(TdApi.Function query) throws ExecutionError { + TdApi.Object object = nativeClientExecute(query); + if (object instanceof TdApi.Error) { + throw new ExecutionError((TdApi.Error) object); + } + if (object == null) { + // unreachable + throw new NullPointerException(); + } + //noinspection unchecked + return (T) object; } /**