This sample illustrates how to handle exceptions in Dapr.
- Dapr CLI.
- Java JDK 11 (or greater):
- Apache Maven version 3.x.
Clone this repository:
git clone https://github.com/dapr/java-sdk.git
cd java-sdk
Then build the Maven project:
# make sure you are in the `java-sdk` (root) directory.
./mvnw clean install
Then get into the examples directory:
cd examples
This example uses the Java SDK Dapr client in order to perform an invalid operation, causing Dapr runtime to return an error. See the code snippet below, from Client.java
:
public class Client {
public static void main(String[] args) throws Exception {
try (DaprClient client = new DaprClientBuilder().build()) {
try {
client.publishEvent("unknown_pubsub", "mytopic", "mydata").block();
} catch (DaprException exception) {
System.out.println("Dapr exception's error code: " + exception.getErrorCode());
System.out.println("Dapr exception's message: " + exception.getMessage());
System.out.println("Dapr exception's reason: " + exception.getStatusDetails().get(
DaprErrorDetails.ErrorDetailType.ERROR_INFO,
"reason",
TypeRef.STRING));
System.out.println("Error's payload size: " + exception.getPayload().length);
}
}
System.out.println("Done");
}
}
dapr run --app-id exception-example -- java -jar target/dapr-java-sdk-examples-exec.jar io.dapr.examples.exception.Client
Once running, the State Client Example should print the output as follows:
== APP == Error code: ERR_PUBSUB_NOT_FOUND
== APP == Error message: ERR_PUBSUB_NOT_FOUND: pubsub unknown_pubsub is not found
== APP == Reason: DAPR_PUBSUB_NOT_FOUND
== APP == Error payload size: 116
...
You can further explore all the error details returned in the DaprException
class.
Before running it in your favorite IDE (like IntelliJ), compile and run the Dapr sidecar first.
- Pre-req:
# make sure you are in the `java-sdk` (root) directory.
./mvnw clean install
- From the examples directory, run:
dapr run --app-id exception-example --dapr-grpc-port=50001 --dapr-http-port=3500
- From your IDE click the play button on the client code and put break points where desired.
To stop the app run (or press CTRL+C
):
dapr stop --app-id exception-example