Skip to content

Commit

Permalink
KOGITO-7453: Extend error handling example to show usage of error code (
Browse files Browse the repository at this point in the history
apache#1341)

* KOGITO-7453: Extend error handling example to show usage of error code

* KOGITO-7453: Replace FQCN in error code with error message

* KOGITO-7453: Apply QE review changes

* Update PublishRestService.java

* Update application.properties

* Create application.properties

* Delete serverless-workflow-examples/serverless-workflow-error-quarkus/src/test/resources/application.properties

* Create application.properties

* Delete serverless-workflow-examples/serverless-workflow-error-quarkus/src/test/resources/application.properties

* Update application.properties

* Update ErrorRestIT.java

---------

Co-authored-by: Francisco Javier Tirado Sarti <65240126+fjtirado@users.noreply.github.com>
  • Loading branch information
2 people authored and rgdoliveira committed Aug 6, 2024
1 parent 0bbd024 commit d4e99d8
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ This example contains a simple workflow service that illustrate error handling.
The service is described using JSON format as defined in the
[CNCF Serverless Workflow specification](https://github.com/serverlessworkflow/specification).

The workflow check if the number is odd or even and print a message indicating that.
The main feature of this demo is that if the number is odd, an exception is thrown, and it is the exception error handling the one that sets the odd message.
The workflow consists of a Java service that determines if a provided number is odd or even, followed by a call to a REST service to publish any even number. The main feature of this demo is to show different ways of exception handling within a workflow. In the Java service, if the number is odd, an exception is thrown, and it is the exception error handling the one that sets the odd message. If the REST service call returns a 400 response, the exception error handling mechanism causes the workflow to follow an error path instead of propagating this exception to the caller.

Hence, this workflow expects JSON input containing a natural number. This number is passed using a service operation to `EvenService` java class. If the number is even, the workflow moves to the next defined state, injecting "even" `numberType`. But if the number is odd, the class throws an `IllegalArgumentException`. This exception is handled and redirected to odd inject node by using [inline workflow error handling](https://github.com/serverlessworkflow/specification/blob/main/specification.md#Workflow-Error-Handling). This basically consists on adding `onErrors` field, where the expected exception is specified in `code` and the target state (a node injecting "odd" `numberType`) in `transition`. Finally, both execution paths finish on the same node, which prints the calculated `eventType`.
Hence, this workflow expects JSON input containing a natural number. This number is passed using a service operation to `EvenService` java class. If the number is even, the workflow moves to the next defined state, injecting "even" `numberType`. But if the number is odd, the class throws an `IllegalArgumentException`. This exception is handled and redirected to odd inject node by using [inline workflow error handling](https://github.com/serverlessworkflow/specification/blob/main/specification.md#Workflow-Error-Handling). This basically consists on adding `onErrors` field, where the expected exception is specified in `code` and the target state (a node injecting "odd" `numberType`) in `transition`. Both execution paths then finish on the same node, which prints the calculated `numberType`.

In the next step, the workflow calls the `PublishRestService` via REST. This service evaluates the `numberType` from the previous step and either returns with a successful response if the number is `even`, or with a failure response (HTTP status code 400) if the number is `odd`. The failure event is handled as the action node contains an `onError` definition. The referenced error is defined as `"code": "HTTP:400"`. If this exception is encountered, the workflow execution continues on an error path that prints out the failure.

As per 0.8 version of the specification, there is no standard way to set a process in error. To do that, users can use a custom metadata key called `errorMessage` which will contain either the error message to be associated to the process instance or an expression that returns the error message to associated to the process instance. In addition to the workflow described before, this example includes a file called `errorWithMEtadata.sw.json` that illustrate the usage of such metadata.

Expand Down Expand Up @@ -103,4 +104,5 @@ In Quarkus you should see the log message printed:

```text
odd
Fail to publish result
```
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,4 @@ public void isEven(int number) {
throw new IllegalArgumentException("Odd situation");
}
}

public void isSquare(int number) {
double sqrt = Math.sqrt(number);
if (sqrt == Math.round(sqrt)) {
throw new RuntimeException("Number has a perfect square");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.examples;

import jakarta.annotation.PostConstruct;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

@Path("/publish")
@Produces(MediaType.APPLICATION_JSON)
public class PublishRestService {

private ObjectMapper objectMapper;
private static final Logger logger = LoggerFactory.getLogger(PublishRestService.class);

@PostConstruct
void init() {
objectMapper = new ObjectMapper();
}

@Path("/{type}/{number}")
@POST
public Response publishEvenNumber(@PathParam("type") String type, @PathParam("number") int number) {
logger.info("Publish type " + type + " number " + number);
// check if the input number is even
if (!"even".equals(type)) {
return Response.status(Status.BAD_REQUEST).entity(objectMapper.createObjectNode().put("error", "Perfect square assessment not supported for odd numbers by this service")).build();
}
return Response.ok().entity(objectMapper.createObjectNode().put("perfect", isPerfectSquare(number))).build();
}

private boolean isPerfectSquare(int number) {
double sqrt = Math.sqrt(number);
return (sqrt == Math.round(sqrt));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,14 @@

# Packaging
# quarkus.package.type=fast-jar

kogito.sw.functions.publishPerfectSquare.host=localhost
kogito.sw.functions.publishPerfectSquare.port=8081
quarkus.native.native-image-xmx=8g

# profile to pack this example into a container, to use it execute activate the maven container profile, -Dcontainer
%container.quarkus.container-image.build=true
%container.quarkus.container-image.push=false
%container.quarkus.container-image.group=${USER}
%container.quarkus.container-image.registry=dev.local
%container.quarkus.container-image.tag=1.0-SNAPSHOT
%container.quarkus.container-image.tag=1.0-SNAPSHOT
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
"errors": [
{
"name": "odd number",
"code": "java.lang.RuntimeException"
"code": "Odd situation"
},
{
"name": "bad request",
"code": "HTTP:400"
}
],
"functions": [
Expand All @@ -18,9 +22,9 @@
"operation": "service:java:org.kie.kogito.examples.EvenService::isEven"
},
{
"name": "isSqr",
"name": "publishPerfectSquare",
"type": "custom",
"operation": "service:java:org.kie.kogito.examples.EvenService::isSquare"
"operation": "rest:post:/publish/{type}/{number}"
},
{
"name": "printMessage",
Expand All @@ -41,15 +45,6 @@
"number": "$.number"
}
}
},
{
"name": "checkSqrAction",
"functionRef": {
"refName": "isSqr",
"arguments": {
"number": "$.number"
}
}
}
],
"transition": "even",
Expand All @@ -66,18 +61,18 @@
"data": {
"numberType": "even"
},
"transition": "finish"
"transition": "print"
},
{
"name": "odd",
"type": "inject",
"data": {
"numberType": "odd"
},
"transition": "finish"
"transition": "print"
},
{
"name": "finish",
"name": "print",
"type": "operation",
"actions": [
{
Expand All @@ -90,6 +85,53 @@
}
}
],
"transition": "publish"
},
{
"name": "publish",
"type": "operation",
"actions": [
{
"name": "publishAction",
"functionRef" : {
"refName": "publishPerfectSquare",
"arguments": {
"type": "$.numberType",
"number": "$.number"
}
}
}
],
"end": true,
"onErrors": [
{
"errorRef": "bad request",
"transition": "setError"
}
]
},
{
"name": "setError",
"type": "inject",
"data": {
"errormessage": "Fail to publish result"
},
"transition": "reportError"
},
{
"name": "reportError",
"type": "operation",
"actions": [
{
"name": "printAction",
"functionRef": {
"refName": "printMessage",
"arguments": {
"message": "errormessage"
}
}
}
],
"end": true
}
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void testErrorRest() {
.post("/error")
.then()
.statusCode(201)
.body("workflowdata.numberType", is("odd"));
.body("workflowdata.numberType", is("even"));
given()
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
Expand Down

0 comments on commit d4e99d8

Please sign in to comment.