Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 12 commits into from
Jul 23, 2024
Merged
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.


## Installing and Running
Expand Down Expand Up @@ -105,4 +106,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 @@ -25,11 +25,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 javax.annotation.PostConstruct;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.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", "No perfect square for odd numbers")).build();
martinweiler marked this conversation as resolved.
Show resolved Hide resolved
}
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
@@ -1,2 +1,5 @@
# Packaging
# quarkus.package.type=fast-jar
# quarkus.package.type=fast-jar

kogito.sw.functions.publishPerfectSquare.host=localhost
kogito.sw.functions.publishPerfectSquare.port=8080
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,9 +85,54 @@
}
}
],
"end": {
"terminate": "true"
}
"transition": "publish"
},
{
"name": "publish",
"type": "operation",
"actions": [
{
"name": "publishAction",
"functionRef" : {
"refName": "publishPerfectSquare",
"arguments": {
"type": "$.numberType",
"number": "$.number"
}
}
martinweiler marked this conversation as resolved.
Show resolved Hide resolved
}
],
"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
}
]
}