Files
Donald Pinckney 0c8586b4c2 Add Java SDK support (#42)
* Add Java SDK reference files (11 files)

Create complete Java reference documentation covering:
- java.md: Entry point with quick start tutorial, key concepts
- patterns.md: 17 patterns (signals, queries, updates, child workflows,
  saga, cancellation scopes, heartbeating, etc.)
- determinism.md: Safe alternatives table, forbidden operations
- determinism-protection.md: Convention-based enforcement (no sandbox)
- error-handling.md: ApplicationFailure, retry/timeout config
- gotchas.md: Non-deterministic operations, cancellation, heartbeating
- testing.md: TestWorkflowEnvironment, Mockito mocking, replay testing
- versioning.md: Workflow.getVersion(), worker versioning
- data-handling.md: Jackson, PayloadConverter, encryption, search attributes
- observability.md: SLF4J logging, Micrometer metrics
- advanced-features.md: Schedules, async completion, worker tuning

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix Java alignment issues from self-review

- Reduce gotchas.md Non-Deterministic Operations from ~94 lines to ~12
  (reference determinism.md instead of duplicating)
- Remove Workflow Failure Exception Types duplication from error-handling.md
  (keep only in advanced-features.md)
- Expand versioning.md Worker Versioning with Key Concepts, PINNED vs
  AUTO_UPGRADE, Deployment Strategies subsections
- Fix section names to match Python reference style:
  Activity Heartbeat Details, Handling Activity Errors,
  Retry Policy Configuration, Workflow Test Environment,
  Mocking Activities, Workflow Replay Testing
- Reduce data-handling.md Payload Encryption verbosity
- Reduce observability.md Logger Customization verbosity
- Reduce testing.md to single approach per section
- Rename determinism.md "Convention-Based Enforcement" to "SDK Protection"
- Fix handler guidance in patterns.md to match Python

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Fix correctness issues in Java reference files

- patterns.md: Fix Queries section — ActivityStub → typed interface
  (Workflow.newActivityStub returns the typed interface, not ActivityStub)
- data-handling.md: Add missing ProtobufPayloadConverter to default
  converter chain (4th of 5 converters)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add Java to SKILL.md and core/determinism.md

- SKILL.md: Add "Temporal Java" trigger phrase, update Overview to
  list Java, add Java entry to Getting Started references
- core/determinism.md: Add Java entry to SDK Protection Mechanisms
  (no sandbox, convention-based, NonDeterministicException at replay)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Apply manual editorial fixes to Java references

- java.md: Remove "Understanding Replay" section (covered by Overview),
  simplify File Organization note (no sandbox rationale)
- gotchas.md: Move Heartbeating before Cancellation, make Wrong Retry
  Classification brief with reference (not inline examples)
- error-handling.md: Remove editorializing from Workflow Failure note
- determinism-protection.md: Remove cross-language comparison paragraph
  (state Java's approach on its own terms)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add temporal-workflowcheck static analysis to Java determinism docs

- determinism-protection.md: Add "Static Analysis with temporal-workflowcheck"
  section with Gradle/Maven setup, manual run, and suppression instructions.
  Beta warning included.
- determinism.md: Update overview and SDK Protection to reference workflowcheck
- core/determinism.md: Update Java entry in SDK Protection Mechanisms

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Integrate feedback from Go PR into Java patterns

- Updates: Add validator note — validators must not mutate state or
  block (matches note added to Python, TypeScript, Go, and core)
- Saga Pattern: Use Workflow.newDetachedCancellationScope() for
  compensations so they execute even if the workflow is cancelled
  (mirrors Go's workflow.NewDisconnectedContext pattern)

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* docs: add @WorkflowInit description to java.md Key Concepts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* mark java as supported

* Apply suggestions from code review

Co-authored-by: Brian Strauch <brian@brianstrauch.com>

* strongly recommend java 21+

* Softened stance on static checker and replay testing.

* address python/typescript sandboxing comment

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Brian Strauch <brian.strauch@temporal.io>
Co-authored-by: Brian Strauch <brian@brianstrauch.com>
2026-04-02 17:07:33 -04:00

189 lines
5.9 KiB
Markdown

# Java SDK Error Handling
## Overview
The Java SDK uses `ApplicationFailure` for application-specific errors and `RetryOptions` for retry configuration. Generally, the following information about errors and retryability applies across activities, child workflows and Nexus operations.
## Application Errors
```java
import io.temporal.activity.ActivityInterface;
import io.temporal.activity.ActivityMethod;
import io.temporal.failure.ApplicationFailure;
@ActivityInterface
public interface OrderActivities {
@ActivityMethod
void validateOrder(Order order);
}
public class OrderActivitiesImpl implements OrderActivities {
@Override
public void validateOrder(Order order) {
if (!order.isValid()) {
throw ApplicationFailure.newFailure(
"Invalid order",
"ValidationError"
);
}
}
}
```
Any exception that is not an `ApplicationFailure` is automatically converted to one, with the fully qualified class name as the type. For example, throwing `new NullPointerException("msg")` is equivalent to `ApplicationFailure.newFailure("msg", "java.lang.NullPointerException")`.
## Non-Retryable Errors
```java
import io.temporal.failure.ApplicationFailure;
public class PaymentActivitiesImpl implements PaymentActivities {
@Override
public String chargeCard(String cardNumber, double amount) {
if (!isValidCard(cardNumber)) {
throw ApplicationFailure.newNonRetryableFailure(
"Permanent failure - invalid credit card",
"PaymentError"
);
}
return processPayment(cardNumber, amount);
}
}
```
You can also mark error types as non-retryable via `RetryOptions.setDoNotRetry()`:
```java
RetryOptions retryOptions = RetryOptions.newBuilder()
.setDoNotRetry(
CreditCardProcessingException.class.getName(),
"ValidationError"
)
.build();
```
Use `newNonRetryableFailure()` when the **activity implementer** knows the error is permanent. Use `setDoNotRetry()` when the **caller** wants to control retryability.
## Activity Errors
Activity failures are always wrapped in `ActivityFailure`. The original exception becomes the `cause`:
- `ActivityFailure` → `ApplicationFailure` (application error)
- `ActivityFailure` → `TimeoutFailure` (timeout)
- `ActivityFailure` → `CanceledFailure` (cancellation)
## Handling Activity Errors
```java
import io.temporal.failure.ActivityFailure;
import io.temporal.failure.ApplicationFailure;
import io.temporal.failure.TimeoutFailure;
import io.temporal.workflow.Workflow;
public class MyWorkflowImpl implements MyWorkflow {
@Override
public String run() {
try {
return activities.riskyOperation();
} catch (ActivityFailure af) {
if (af.getCause() instanceof ApplicationFailure) {
ApplicationFailure appFailure = (ApplicationFailure) af.getCause();
String type = appFailure.getType();
// Handle based on error type
} else if (af.getCause() instanceof TimeoutFailure) {
// Handle timeout
}
throw ApplicationFailure.newFailure(
"Workflow failed due to activity error",
"WorkflowError"
);
}
}
}
```
## Retry Policy Configuration
```java
import io.temporal.activity.ActivityOptions;
import io.temporal.common.RetryOptions;
import io.temporal.workflow.Workflow;
import java.time.Duration;
public class MyWorkflowImpl implements MyWorkflow {
private final MyActivities activities = Workflow.newActivityStub(
MyActivities.class,
ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofMinutes(10))
.setRetryOptions(RetryOptions.newBuilder()
.setMaximumInterval(Duration.ofMinutes(1))
.setMaximumAttempts(5)
.setDoNotRetry("ValidationError", "PaymentError")
.build())
.build()
);
@Override
public String run() {
return activities.myActivity();
}
}
```
Only set options such as `maximumInterval`, `maximumAttempts` etc. if you have a domain-specific reason to. If not, prefer to leave them at their defaults.
## Timeout Configuration
```java
ActivityOptions options = ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofMinutes(5)) // Single attempt
.setScheduleToCloseTimeout(Duration.ofMinutes(30)) // Including retries
.setHeartbeatTimeout(Duration.ofMinutes(2)) // Between heartbeats
.build();
```
## Workflow Failure
**IMPORTANT:** Only `ApplicationFailure` causes a workflow to fail. Any other exception thrown from workflow code causes the workflow task to retry indefinitely, not the workflow itself.
```java
import io.temporal.failure.ApplicationFailure;
public class MyWorkflowImpl implements MyWorkflow {
@Override
public String run() {
if (someCondition) {
throw ApplicationFailure.newFailure(
"Cannot process order",
"BusinessError"
);
}
return "success";
}
}
```
To allow other exception types to fail the workflow instead of causing infinite task retries, see `references/java/advanced-features.md` for configuring `setFailWorkflowExceptionTypes()`.
Use checked exceptions with `Workflow.wrap()` to rethrow them as unchecked:
```java
try {
return someCall();
} catch (Exception e) {
throw Workflow.wrap(e);
}
```
## Best Practices
1. Use specific error types for different failure modes
2. Mark permanent failures as non-retryable
3. Configure appropriate retry policies
4. Log errors before re-raising
5. Catch `ActivityFailure` (not `ApplicationFailure`) for activity failures in workflows
6. Design code to be idempotent for safe retries (see more at `references/core/patterns.md`)
7. Use `ApplicationFailure.newFailure()` to fail workflows — other exceptions cause infinite task retries