Files
Donald Pinckney 44eba4e91c Add .NET SDK support to temporal-developer skill (#39)
* Add .NET reference files for temporal-developer skill

Created 11 .NET reference files covering: dotnet.md (overview/quick start),
patterns.md, determinism.md, determinism-protection.md, error-handling.md,
testing.md, versioning.md, observability.md, data-handling.md, gotchas.md,
and advanced-features.md. Follows Python/TypeScript patterns with .NET-specific
content for Task determinism, CancellationToken, dependency injection, etc.

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

* Fix .NET alignment issues from self-review

- dotnet.md: Reduce Determinism Rules section to brief cross-reference
  (was duplicating determinism.md content)
- patterns.md: Add ParentClosePolicy to Child Workflows example
- gotchas.md: Add missing "Heartbeat Timeout Too Short" subsection
- versioning.md: Add missing Key Concepts, Deployment Strategies,
  Query Filters, PINNED/AUTO_UPGRADE guidance, CLI examples
- advanced-features.md: Add worker-level heading for exception types

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

* Fix .NET correctness issues from verification pass

- patterns.md: Fix cancellation pattern to use official
  TemporalException.IsCanceledException(e) with detached CancellationTokenSource
- advanced-features.md: Fix DI hosting example to use official
  AddHostedTemporalWorker(clientTargetHost:, clientNamespace:, taskQueue:) pattern

Verified against official SDK README, API docs, and temporal-docs.

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

* Update supported language references to include .NET

- SKILL.md: Add "Temporal .NET" and "Temporal C#" trigger phrases,
  update overview to mention .NET, add .NET entry in getting started
- core/determinism.md: Add .NET entry in SDK Protection Mechanisms

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

* Edits to advanced features

* edits to determinism protection, and move the .editorconfig section

* missed one

* edit determinism.md

* edit error-handling.md

* edit gotchas.md

* edit patterns.md

* edit versioning.md

* edit observability.md

* fix metrics

* self-review round 1

* minor correctness fixed

* Update references/dotnet/patterns.md

Co-authored-by: Justin Anderson <44687433+jmaeagle99@users.noreply.github.com>

* address comments, clarify reference to earlier code snippet

* clarify that operations are forbidden IN WORKFLOWS

* cleanup workflow cancellation handling example

* add task token retrieval comment

* update .net requirements

* Fix propagation of workflow cancellation

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Justin Anderson <44687433+jmaeagle99@users.noreply.github.com>
2026-04-17 14:28:02 -04:00

194 lines
6.1 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.CanceledFailure;
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) {
// Let cancellation propagate so the workflow is canceled, not failed
if (af.getCause() instanceof CanceledFailure) {
throw 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