From 5fb6c3d0cc60fd5d169a368ef3422d61cd04b900 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Heredero?= Date: Wed, 8 Nov 2023 09:56:05 +0100 Subject: [PATCH] Task 2 - errors handler --- src/main/java/CalculatorClient.java | 31 +++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/java/CalculatorClient.java b/src/main/java/CalculatorClient.java index 0d86333..fbeb916 100644 --- a/src/main/java/CalculatorClient.java +++ b/src/main/java/CalculatorClient.java @@ -2,24 +2,42 @@ import ch.sdi.calc.CalculatorGrpc; import ch.sdi.calc.CalculatorOuterClass; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.StatusRuntimeException; + +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; public class CalculatorClient { private ManagedChannel channel; - private final CalculatorGrpc.CalculatorBlockingStub blockingStub; + private CalculatorGrpc.CalculatorBlockingStub blockingStub = null; + private static final Logger logger = Logger.getLogger(CalculatorClient.class.getName()); public CalculatorClient(String host, int port) { this(ManagedChannelBuilder.forAddress(host, port).usePlaintext()); } private CalculatorClient(ManagedChannelBuilder channelBuilder) { - channel = channelBuilder.build(); + try { + channel = channelBuilder.build(); + } catch (Exception e) { + logger.log(Level.WARNING, "Could not connect to server: {0}", e.getMessage()); + return; + } blockingStub = CalculatorGrpc.newBlockingStub(channel); } public double calculate(String expression) { + logger.info("Trying to do: " + expression + " ..." ); CalculatorOuterClass.CalculatorRequest request = CalculatorOuterClass.CalculatorRequest.newBuilder().setExpression(expression).build(); - CalculatorOuterClass.CalculatorResponse response; - response = blockingStub.calculate(request); + CalculatorOuterClass.CalculatorResponse response = null; + try { + response = blockingStub.calculate(request); + } catch (StatusRuntimeException e) { + logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); + return 0; + } + logger.info("Answer: " + response.getResult()); return response.getResult(); } @@ -32,5 +50,10 @@ public class CalculatorClient { double answer = client.calculate(expression); System.out.println("Answer: " + answer); } + + String expression = "1-a"; + System.out.println("Expression: " + expression); + double answer = client.calculate(expression); + System.out.println("Answer: " + answer); } }