diff --git a/assets/css/index.css b/assets/css/index.css index 111532dd19..7978ee7063 100644 --- a/assets/css/index.css +++ b/assets/css/index.css @@ -88,6 +88,12 @@ section.prose { @apply bg-slate-900 rounded-lg; } +.prose pre.mermaid { + background-color: white !important; + border-radius: 0.5rem; + padding: 1rem; +} + .prose pre > code { @apply bg-none font-monogeist; } diff --git a/content/develop/clients/dotnet/error-handling.md b/content/develop/clients/dotnet/error-handling.md new file mode 100644 index 0000000000..965a97f477 --- /dev/null +++ b/content/develop/clients/dotnet/error-handling.md @@ -0,0 +1,147 @@ +--- +title: Error handling +description: Learn how to handle errors when using NRedisStack. +linkTitle: Error handling +weight: 60 +--- + +NRedisStack uses **exceptions** to signal errors. Code examples in the documentation often omit error handling for brevity, but it is essential in production code. This page explains how NRedisStack's error handling works and how to apply common error handling patterns. + +For an overview of error types and handling strategies, see [Error handling]({{< relref "/develop/clients/error-handling" >}}). +See also [Production usage]({{< relref "/develop/clients/dotnet/produsage" >}}) +for more information on connection management, timeouts, and other aspects of +app reliability. + +## Exception types + +NRedisStack throws exceptions to signal errors. Common exception types include: + +| Exception | When it occurs | Recoverable | Recommended action | +|---|---|---|---| +| `RedisConnectionException` | Connection refused or lost | ✅ | Retry with backoff or fall back | +| `RedisTimeoutException` | Operation exceeded timeout | ✅ | Retry with backoff | +| `RedisCommandException` | Invalid command or arguments | ❌ | Fix the command or arguments | +| `RedisServerException` | Invalid operation on server | ❌ | Fix the operation or data | + +See [Categories of errors]({{< relref "/develop/clients/error-handling#categories-of-errors" >}}) +for a more detailed discussion of these errors and their causes. + +## Applying error handling patterns + +The [Error handling]({{< relref "/develop/clients/error-handling" >}}) overview +describes four main patterns. The sections below show how to implement them in +NRedisStack: + +### Pattern 1: Fail fast + +Catch specific exceptions that represent unrecoverable errors and re-throw them (see +[Pattern 1: Fail fast]({{< relref "/develop/clients/error-handling#pattern-1-fail-fast" >}}) +for a full description): + +```csharp +using NRedisStack; +using StackExchange.Redis; + +var muxer = ConnectionMultiplexer.Connect("localhost:6379"); +var db = muxer.GetDatabase(); + +try { + var result = db.StringGet("key"); +} catch (RedisCommandException) { + // This indicates a bug in the code, such as using + // StringGet on a list key. + throw; +} +``` + +### Pattern 2: Graceful degradation + +Catch specific errors and fall back to an alternative, where possible (see +[Pattern 2: Graceful degradation]({{< relref "/develop/clients/error-handling#pattern-2-graceful-degradation" >}}) +for a full description): + +```csharp +try { + var cachedValue = db.StringGet(key); + return cachedValue.ToString(); +} catch (RedisConnectionException) { + logger.LogWarning("Cache unavailable, using database"); + + // Fallback to database + return database.Get(key); +} +``` + +### Pattern 3: Retry with backoff + +Retry on temporary errors such as timeouts (see +[Pattern 3: Retry with backoff]({{< relref "/develop/clients/error-handling#pattern-3-retry-with-backoff" >}}) +for a full description): + +```csharp +const int maxRetries = 3; +int retryDelay = 100; + +for (int attempt = 0; attempt < maxRetries; attempt++) { + try { + return db.StringGet(key).ToString(); + } catch (RedisTimeoutException) { + if (attempt < maxRetries - 1) { + Thread.Sleep(retryDelay); + retryDelay *= 2; // Exponential backoff + } else { + throw; + } + } +} +``` + +See also [Timeouts]({{< relref "/develop/clients/dotnet/produsage#timeouts" >}}) +for more information on configuring timeouts in NRedisStack. + +### Pattern 4: Log and continue + +Log non-critical errors and continue (see +[Pattern 4: Log and continue]({{< relref "/develop/clients/error-handling#pattern-4-log-and-continue" >}}) +for a full description): + +```csharp +try { + db.StringSet(key, value, TimeSpan.FromSeconds(3600)); +} catch (RedisConnectionException) { + logger.LogWarning($"Failed to cache {key}, continuing without cache"); + // Application continues normally +} +``` + +## Async error handling + +Error handling works the usual way with `async`/`await`, as shown in the +example below: + +```csharp +using NRedisStack; +using StackExchange.Redis; + +var muxer = ConnectionMultiplexer.Connect("localhost:6379"); +var db = muxer.GetDatabase(); + +async Task GetWithFallbackAsync(string key) { + try { + var result = await db.StringGetAsync(key); + if (result.HasValue) { + return result.ToString(); + } + } catch (RedisConnectionException) { + logger.LogWarning("Cache unavailable"); + return await database.GetAsync(key); + } + + return await database.GetAsync(key); +} +``` + +## See also + +- [Error handling]({{< relref "/develop/clients/error-handling" >}}) +- [Production usage]({{< relref "/develop/clients/dotnet/produsage" >}}) diff --git a/content/develop/clients/dotnet/produsage.md b/content/develop/clients/dotnet/produsage.md index 7792a6449f..e992821add 100644 --- a/content/develop/clients/dotnet/produsage.md +++ b/content/develop/clients/dotnet/produsage.md @@ -112,6 +112,9 @@ the most common Redis exceptions: [stream entry]({{< relref "/develop/data-types/streams#entry-ids" >}}) using an invalid ID). +See [Error handling]({{< relref "/develop/clients/dotnet/error-handling" >}}) +for more information on handling exceptions. + ### Retries During the initial `ConnectionMultiplexer.Connect()` call, `NRedisStack` will diff --git a/content/develop/clients/error-handling.md b/content/develop/clients/error-handling.md new file mode 100644 index 0000000000..1a81fb0d2f --- /dev/null +++ b/content/develop/clients/error-handling.md @@ -0,0 +1,379 @@ +--- +title: Error handling +description: Learn how to handle errors when using Redis client libraries. +linkTitle: Error handling +weight: 50 +--- + +When working with Redis, errors can occur for various reasons, including network issues, invalid commands, or resource constraints. This guide explains the types of errors you might encounter and how to handle them effectively. + +## Categories of errors + +Redis errors fall into four main categories. The table below provides a quick overview of each type. Click on any error type to jump to its detailed section, which includes common causes, examples, handling strategies, and code examples. + +| Error Type | Common Causes | When to Handle | Examples | +|---|---|---|---| +| [Connection errors](#connection-errors) | Network issues, server down, auth failure, timeouts, pool exhaustion | Almost always | `ConnectionError`, `TimeoutError`, `AuthenticationError` | +| [Command errors](#command-errors) | Typo in command, wrong arguments, invalid types, unsupported command | Rarely (usually indicates a bug) | `ResponseError`, `WRONGTYPE`, `ERR unknown command` | +| [Data errors](#data-errors) | Serialization failures, corrupted data, type mismatches | Sometimes (depends on data source) | `JSONDecodeError`, `SerializationError`, `WRONGTYPE` | +| [Resource errors](#resource-errors) | Memory limit, pool exhausted, too many connections, key eviction | Sometimes (some are temporary) | `OOM`, pool timeout, `LOADING` | + +### Connection errors + +Connection errors occur when your application cannot communicate with Redis. These are typically temporary and often recoverable. + +**Common causes:** +- Network connectivity issues +- Redis server is down or unreachable +- Authentication failure +- Connection timeout +- Connection pool exhaustion + +**Examples:** +- `ConnectionError`: Network failure or server unreachable +- `TimeoutError`: Operation exceeded the configured timeout +- `AuthenticationError`: Invalid credentials + +**When to handle:** Almost always. Connection errors are usually temporary, so implementing retry logic or fallback strategies is recommended. + +**Example strategy:** + +```mermaid {width="80%"} +graph TB + A["Try to connect
to Redis"] + A -->|Success| B(["Use the result"]) + A -->|Failure| C{Error type?} + C -->|Timeout| D(["Retry with
exponential backoff"]) + C -->|Auth failure| E(["Check credentials
and fail"]) + C -->|Network error| F(["Fallback to
alternative data source"]) +``` + +### Command errors + +Command errors occur when Redis receives an invalid or malformed command. These typically indicate a bug in your code. + +**Common causes:** +- Typo in command name +- Wrong number of arguments +- Invalid argument types (for example, supplying a + [string]({{< relref "/develop/data-types/strings" >}}) key to a + [list]({{< relref "/develop/data-types/lists" >}}) command)) +- Using a command that doesn't exist in your Redis version + +**Examples:** +- `ResponseError`: Invalid command or syntax error +- `WRONGTYPE Operation against a key holding the wrong kind of value` +- `ERR unknown command` + +**When to handle:** Rarely. These usually indicate programming error and so you +should fix the errors in your code rather than attempt to handle them at runtime. However, some cases (like invalid user input) may be worth handling. + +**Example:** + +```mermaid {width="60%"} +graph TB + A["User provides
JSONPath expression"] + A --> B["Try to execute it"] + direction TB + B -->|ResponseError| C["Log the error"] + C --> D(["Return default value
or error message to user"]) + B -->|Success| E(["Use the result"]) +``` + +### Data errors + +Data errors occur when there are problems with the data itself, such as +serialization failures, or data corruption. + +**Common causes:** +- Object cannot be serialized to JSON +- Cached data is corrupted +- Attempting to deserialize invalid data + +**Examples:** +- `JSONDecodeError`: Cannot deserialize JSON data +- `SerializationError`: Cannot serialize object + +**When to handle:** Sometimes. If the error is due to user input or external data, handle it gracefully. If it's due to your code, fix the code. + +**Example:** + +```mermaid {width="50%"} +graph TB + A["Read cached data"] + A --> B["Try to deserialize"] + B -->|Success| C(["Use the data"]) + B -->|Deserialization fails| D["Log the error"] + D --> E["Delete corrupted
cache entry"] + E --> F(["Fetch fresh data
from source"]) +``` + +### Resource errors + +Resource errors occur when Redis runs out of resources or hits limits. + +**Common causes:** +- Memory limit reached +- Connection pool exhausted +- Too many connections +- Key eviction due to memory pressure + +**Examples:** +- `OOM command not allowed when used memory > 'maxmemory'` +- Connection pool timeout +- `LOADING Redis is loading the dataset in memory` + +**When to handle:** Sometimes. Some resource errors are temporary (Redis loading), while others indicate a configuration problem. + +**Example:** + +```mermaid {width="80%"} +graph TB + A{Resource error
occurred?} + A -->|Redis loading| B(["Retry after
a delay"]) + A -->|Memory full| C(["Check Redis
configuration and data"]) + A -->|Pool exhausted| D(["Increase pool size
or reduce concurrency"]) +``` + +## Error handling patterns + +### Pattern 1: Fail fast + +Use this when the error is unrecoverable or indicates a bug in your code. + +**When to use:** + +- Command errors (invalid syntax) +- Authentication errors +- Programming errors + +**Example:** + +```python +try: + result = r.get(key) +except redis.ResponseError as e: + # This indicates a bug in our code + raise # Re-raise the exception +``` + +### Pattern 2: Graceful degradation + +Use this when you have an alternative way to get the data you need, so you can +fall back to using the alternative instead of the preferred code. + +**When to use:** + +- Cache reads (fallback to database) +- Session reads (fallback to default values) +- Optional data (skip if unavailable) + +**Example:** + +```python +try: + cached_value = r.get(key) + if cached_value: + return cached_value +except redis.ConnectionError: + logger.warning("Cache unavailable, using database") + +# Fallback to database +return database.get(key) +``` + +### Pattern 3: Retry with backoff + +Use this when the error could be due to network load or other temporary +conditions. + +**When to use:** + +- Connection timeouts +- Temporary network issues +- Redis loading data + +**Example:** + +```python +import time + +max_retries = 3 +retry_delay = 0.1 + +for attempt in range(max_retries): + try: + return r.get(key) + except redis.TimeoutError: + if attempt < max_retries - 1: + time.sleep(retry_delay) + retry_delay *= 2 # Exponential backoff + else: + raise +``` + +Note that client libraries often implement retry logic for you, so +you may just need to provide the right configuration rather than +implementing retries yourself. See [Client-specific error handling](#client-specific-error-handling) below for links to pages that +describe retry configuration for each client library. + +### Pattern 4: Log and continue + +Use this when the operation is not critical to your application. + +**When to use:** + +- Cache writes (data loss is acceptable) +- Non-critical updates +- Metrics collection + +**Example:** + +```python +try: + r.setex(key, 3600, value) +except redis.ConnectionError: + logger.warning(f"Failed to cache {key}, continuing without cache") + # Application continues normally +``` + +## Decision tree: How to handle errors + +```mermaid +graph LR + Start{Error occurred?} + + Start -->|Connection error| C1{Operation type?} + C1 -->|Read| C2["Graceful degradation
fallback"] + C1 -->|Write| C3["Log and continue
or retry"] + C1 -->|Critical| C4["Retry with backoff"] + + Start -->|Command error| Cmd1{Error source?} + Cmd1 -->|User input| Cmd2["Log and return
error to user"] + Cmd1 -->|Your code| Cmd3["Fail fast
fix the bug"] + + Start -->|Data error| D1{Operation type?} + D1 -->|Read| D2["Log, invalidate,
fallback"] + D1 -->|Write| D3["Log and fail
data is invalid"] + + Start -->|Resource error| R1{Error type?} + R1 -->|Redis loading| R2["Retry with backoff"] + R1 -->|Pool exhausted| R3["Increase pool size"] + R1 -->|Memory full| R4["Check configuration"] +``` + +## Logging and monitoring + +In production, you may find it useful to log errors when they +occur and monitor the logs for patterns. This can help you identify +which errors are most common and whether your retry and fallback +strategies are effective. + +### What to log + +- **Error type and message:** What went wrong? +- **Context:** Which key? Which operation? +- **Timestamp:** When did it happen? +- **Retry information:** Is this a retry? How many attempts? + +**Example:** +```python +logger.error( + "Redis operation failed", + extra={ + "error_type": type(e).__name__, + "operation": "get", + "key": key, + "attempt": attempt, + "timestamp": datetime.now().isoformat(), + } +) +``` + +### What to monitor + +- **Error rate:** How many errors per minute? +- **Error types:** Which errors are most common? +- **Recovery success:** How many retries succeed? +- **Fallback usage:** How often do we use fallback strategies? + +These metrics help you identify patterns and potential issues. + +## Common mistakes + +### Catching all exceptions + +**Problem:** If you catch all exceptions, you might catch unexpected +errors and hide bugs. + +**Example (wrong):** + +```python +try: + result = r.get(key) +except Exception: # Too broad - some errors indicate code problems. + pass +``` + +**Better approach:** Catch specific exception types. + +**Example (correct):** + +```python +try: + result = r.get(key) +except redis.ConnectionError: + # Handle connection error + pass +``` + +### Not distinguishing error types + +**Problem:** Different errors need different handling. For example, retrying a syntax error won't help. + +**Example (wrong):** + +```python +try: + result = r.get(key) +except redis.ResponseError: + # Retry? This won't help if it's a syntax error. + retry() +``` + +**Better approach:** Handle each error type differently based on whether or not +it is recoverable. + +**Example (correct):** + +```python +try: + result = r.get(key) +except redis.TimeoutError: + retry() # Retry on timeout +except redis.ResponseError: + raise # Fail on syntax error +``` + +### Ignoring connection pool errors + +**Problem:** Connection pool errors indicate a configuration or concurrency issue that needs to be addressed. + +**Example (wrong):** + +```python +# Pool is exhausted, but we don't handle it +result = r.get(key) # Might timeout waiting for connection +``` + +**Better approach:** Monitor pool usage and increase size if needed. + +## Client-specific error handling + +For detailed information about exceptions in your client library, see: + +- [redis-py error handling]({{< relref "/develop/clients/redis-py/error-handling" >}}) +- [Node.js error handling]({{< relref "/develop/clients/nodejs/error-handling" >}}) +- [Java (Jedis) error handling]({{< relref "/develop/clients/jedis/error-handling" >}}) +- [Go (go-redis) error handling]({{< relref "/develop/clients/go/error-handling" >}}) +- [.NET (NRedisStack) error handling]({{< relref "/develop/clients/dotnet/error-handling" >}}) diff --git a/content/develop/clients/go/error-handling.md b/content/develop/clients/go/error-handling.md new file mode 100644 index 0000000000..984becd2a8 --- /dev/null +++ b/content/develop/clients/go/error-handling.md @@ -0,0 +1,117 @@ +--- +title: Error handling +description: Learn how to handle errors when using go-redis +linkTitle: Error handling +weight: 50 +--- + +go-redis uses **explicit error returns** following Go's idiomatic error handling pattern. Code examples in the documentation often omit error handling for brevity, +but it is essential in production code. +This page explains how go-redis's error handling works and how to apply +some common error handling patterns. For an overview of error types and handling +strategies, see [Error handling]({{< relref "/develop/clients/error-handling" >}}). +See also [Production usage]({{< relref "/develop/clients/go/produsage" >}}) +for more information on connection management, timeouts, and other aspects of +app reliability. + +## Error handling in Go + +In Go, functions return errors as a second return value. You can check for errors explicitly with code like the following: + +```go +result, err := rdb.Get(ctx, key).Result() +if err != nil { + // Handle the error +} +``` + +Common error types from go-redis include: + +| Error | When it occurs | Recoverable | Recommended action | +|---|---|---|---| +| `redis.Nil` | Key does not exist | ✅ | Return default value or fetch from source | +| `context.DeadlineExceeded` | Operation timeout | ✅ | Retry with backoff | +| `net.OpError` | Network error | ✅ | Retry with backoff or fall back to alternative | +| `redis.ResponseError` | Redis error response | ❌ | Fix the command or arguments | + +See [Categories of errors]({{< relref "/develop/clients/error-handling#categories-of-errors" >}}) +for a more detailed discussion of these errors and their causes. + +## Applying error handling patterns + +The [Error handling]({{< relref "/develop/clients/error-handling" >}}) overview +describes four main patterns. The sections below show how to implement them in +go-redis: + +### Pattern 1: Fail fast + +Return the error immediately if it represents an unrecoverable situation (see +[Pattern 1: Fail fast]({{< relref "/develop/clients/error-handling#pattern-1-fail-fast" >}}) +for a full description): + +```go +result, err := rdb.Get(ctx, key).Result() +if err != nil { + // This indicates a problem that should be fixed + return err +} +``` + +### Pattern 2: Graceful degradation + +Check for specific errors and fall back to an alternative (see +[Pattern 2: Graceful degradation]({{< relref "/develop/clients/error-handling#pattern-2-graceful-degradation" >}}) +for a full description): + +```go +result, err := rdb.Get(ctx, key).Result() +if err != nil { + if err == redis.Nil { + // Key doesn't exist, try database + return database.Get(ctx, key) + } + if _, ok := err.(net.Error); ok { + // Network error, use fallback + logger.Warn("Cache unavailable, using database") + return database.Get(ctx, key) + } + return err +} +return result, nil +``` + +### Pattern 3: Retry with backoff + +Retry on temporary errors such as timeouts (see +[Pattern 3: Retry with backoff]({{< relref "/develop/clients/error-handling#pattern-3-retry-with-backoff" >}}) +for a full description). go-redis has built-in retry logic with +configurable timing and backoffs. See [Retries]({{< relref "/develop/clients/go/produsage#retries" >}}) for more information. Note also that +you can configure timeouts (which are one of the most common causes of +temporary errors) for connections and commands. See [Timeouts]({{< relref "/develop/clients/go/produsage#timeouts" >}}) for more information. + +### Pattern 4: Log and continue + +Log non-critical errors and continue (see +[Pattern 4: Log and continue]({{< relref "/develop/clients/error-handling#pattern-4-log-and-continue" >}}) +for a full description): + +```go +err := rdb.SetEx(ctx, key, value, 3600*time.Second).Err() +if err != nil { + if _, ok := err.(net.Error); ok { + logger.Warnf("Failed to cache %s, continuing without cache", key) + // Application continues normally + } else { + return err + } +} +``` + +Note that go-redis also supports [OpenTelemetry](https://opentelemetry.io/) +instrumentation to monitor performance and trace the execution of Redis commands. See [Observability]({{< relref "/develop/clients/go#observability" >}}) for more information. + +## See also + +- [Error handling]({{< relref "/develop/clients/error-handling" >}}) +- [Production usage]({{< relref "/develop/clients/go/produsage" >}}) +- [Observability]({{< relref "/develop/clients/go#observability" >}}) diff --git a/content/develop/clients/go/produsage.md b/content/develop/clients/go/produsage.md index 695ffd1015..48a01dafe7 100644 --- a/content/develop/clients/go/produsage.md +++ b/content/develop/clients/go/produsage.md @@ -64,6 +64,9 @@ you should also always check that the error value is `nil` before proceeding. Errors can be returned for failed connections, network problems, and invalid command parameters, among other things. +See [Error handling]({{< relref "/develop/clients/go/error-handling" >}}) for a +more detailed discussion of error handling approaches in `go-redis`. + ### Monitor performance and errors `go-redis` supports [OpenTelemetry](https://opentelemetry.io/). This lets diff --git a/content/develop/clients/jedis/error-handling.md b/content/develop/clients/jedis/error-handling.md new file mode 100644 index 0000000000..528a6ed082 --- /dev/null +++ b/content/develop/clients/jedis/error-handling.md @@ -0,0 +1,137 @@ +--- +title: Error handling +description: Learn how to handle errors when using Jedis. +linkTitle: Error handling +weight: 50 +--- + +Jedis uses **exceptions** to signal errors. Code examples in the documentation often omit error handling for brevity, but it is essential in production code. This page explains how Jedis's error handling works and how to apply common error handling patterns. + +For an overview of error types and handling strategies, see [Error handling]({{< relref "/develop/clients/error-handling" >}}). +See also [Production usage]({{< relref "/develop/clients/jedis/produsage" >}}) +for more information on connection management, timeouts, and other aspects of +app reliability. + +## Exception hierarchy + +Jedis organizes exceptions in a hierarchy rooted at `JedisException`, which extends `RuntimeException`. All Jedis exceptions are unchecked exceptions: + +``` +JedisException +├── JedisDataException +│ ├── JedisRedirectionException +│ │ ├── JedisMovedDataException +│ │ └── JedisAskDataException +│ ├── AbortedTransactionException +│ ├── JedisAccessControlException +│ └── JedisNoScriptException +├── JedisClusterException +│ ├── JedisClusterOperationException +│ ├── JedisConnectionException +│ └── JedisValidationException +└── InvalidURIException +``` + +### Key exceptions + +The following exceptions are the most commonly encountered in Jedis applications. +See [Categories of errors]({{< relref "/develop/clients/error-handling#categories-of-errors" >}}) +for a more detailed discussion of these errors and their causes. + +| Exception | When it occurs | Recoverable | Recommended action | +|---|---|---|---| +| `JedisConnectionException` | Connection lost or closed unexpectedly | ✅ | Retry with backoff or fall back | +| `JedisAccessControlException` | Authentication failure or permission denied | ❌ | Fix credentials or permissions | +| `JedisDataException` | Problem with data being sent or received | ❌ | Fix the data or command | +| `JedisException` | Unexpected errors (catch-all) | ❌ | Log and investigate | + +## Applying error handling patterns + +The [Error handling]({{< relref "/develop/clients/error-handling" >}}) overview +describes four main patterns. The sections below show how to implement them in +Jedis: + +### Pattern 1: Fail fast + +Catch specific exceptions that represent unrecoverable errors and re-throw them (see +[Pattern 1: Fail fast]({{< relref "/develop/clients/error-handling#pattern-1-fail-fast" >}}) +for a full description): + +```java +try (Jedis jedis = jedisPool.getResource()) { + String result = jedis.get(key); +} catch (JedisDataException e) { + // This indicates a bug in our code + throw e; +} +``` + +### Pattern 2: Graceful degradation + +Catch specific errors and fall back to an alternative, where possible (see +[Pattern 2: Graceful degradation]({{< relref "/develop/clients/error-handling#pattern-2-graceful-degradation" >}}) +for a full description): + +```java +try (Jedis jedis = jedisPool.getResource()) { + String cachedValue = jedis.get(key); + if (cachedValue != null) { + return cachedValue; + } +} catch (JedisConnectionException e) { + logger.warn("Cache unavailable, using database"); + return database.get(key); +} + +// Fallback to database +return database.get(key); +``` + +### Pattern 3: Retry with backoff + +Retry on temporary errors like connection failures (see +[Pattern 3: Retry with backoff]({{< relref "/develop/clients/error-handling#pattern-3-retry-with-backoff" >}}) +for a full description): + +```java +int maxRetries = 3; +int retryDelay = 100; + +for (int attempt = 0; attempt < maxRetries; attempt++) { + try (Jedis jedis = jedisPool.getResource()) { + return jedis.get(key); + } catch (JedisConnectionException e) { + if (attempt < maxRetries - 1) { + try { + Thread.sleep(retryDelay); + retryDelay *= 2; // Exponential backoff + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException(ie); + } + } else { + throw e; + } + } +} +``` + +### Pattern 4: Log and continue + +Log non-critical errors and continue (see +[Pattern 4: Log and continue]({{< relref "/develop/clients/error-handling#pattern-4-log-and-continue" >}}) +for a full description): + +```java +try (Jedis jedis = jedisPool.getResource()) { + jedis.setex(key, 3600, value); +} catch (JedisConnectionException e) { + logger.warn("Failed to cache " + key + ", continuing without cache"); + // Application continues normally +} +``` + +## See also + +- [Error handling]({{< relref "/develop/clients/error-handling" >}}) +- [Production usage]({{< relref "/develop/clients/jedis/produsage" >}}) diff --git a/content/develop/clients/nodejs/error-handling.md b/content/develop/clients/nodejs/error-handling.md new file mode 100644 index 0000000000..0ed52b4fbf --- /dev/null +++ b/content/develop/clients/nodejs/error-handling.md @@ -0,0 +1,184 @@ +--- +title: Error handling +description: Learn how to handle errors when using node-redis. +linkTitle: Error handling +weight: 6 +--- + +node-redis uses +[**promises**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) +for error handling. Most Redis JavaScript examples +throughout the documentation mainly show the "happy path" and omit error +handling for brevity. This page shows how to apply error handling +techniques in node-redis for real world code. +For an overview of some common general error types and strategies for +handling them, see +[Error handling]({{< relref "/develop/clients/error-handling" >}}). +See also [Production usage]({{< relref "/develop/clients/nodejs/produsage" >}}) +for more information on connection management, timeouts, and other aspects of +app reliability. + + +## Common error types + +node-redis throws errors as rejected promises. Common error types include: + +| Error | When it occurs | Recoverable | Recommended action | +|---|---|---|---| +| `ECONNREFUSED` | Connection refused | ✅ | Retry with backoff or fall back | +| `ETIMEDOUT` | Command timeout | ✅ | Retry with backoff | +| `ECONNRESET` | Connection reset by peer | ✅ | Retry with backoff | +| `EAI_AGAIN` | DNS resolution failure | ✅ | Retry with backoff | +| `ReplyError` (`WRONGTYPE`) | Type mismatch | ❌ | Fix schema or code | +| `ReplyError` (`BUSY`, `TRYAGAIN`, `LOADING`) | Redis busy/loading | ⚠️ | Retry with backoff (bounded) | + +See [Categories of errors]({{< relref "/develop/clients/error-handling#categories-of-errors" >}}) +for a more detailed discussion of these errors and their causes. + +## Async/await in examples + +The examples on this page and throughout the node-redis docs use `async/await` +style for clarity. + +```javascript +// Using async/await (shown in examples below) +try { + const result = await client.get(key); + // Handle success +} catch (error) { + // Handle error +} +``` + +Alternatively, you can use promise chains with `.then()` and `.catch()`: + +```javascript +// Using promise chains (equivalent approach) +client.get(key) + .then(result => { + // Handle success + }) + .catch(error => { + // Handle error + }); +``` + +## Error events + +Node-Redis provides [multiple events to handle various scenarios](https://github.com/redis/node-redis?tab=readme-ov-file#events), among which the most critical is the `error` event. + +This event is triggered whenever an error occurs within the client. + +It is crucial to listen for error events. + +If a client does not register at least one error listener and an error occurs, the system will throw that error, potentially causing the Node.js process to exit unexpectedly. +See [the EventEmitter docs](https://nodejs.org/api/events.html#events_error_events) for more details. + +```typescript +const client = createClient({ + // ... client options +}); +// Always ensure there's a listener for errors in the client to prevent process crashes due to unhandled errors +client.on('error', error => { + console.error(`Redis client error:`, error); +}); +``` + +## Applying error handling patterns + +The [Error handling]({{< relref "/develop/clients/error-handling" >}}) +overview describes four common error handling patterns. The sections +below show how to implement these patterns in node-redis: + +### Pattern 1: Fail fast + +Catch specific errors that represent unrecoverable errors and re-throw them (see +[Pattern 1: Fail fast]({{< relref "/develop/clients/error-handling#pattern-1-fail-fast" >}}) +for a full description). + +```javascript +try { + await client.get(key); +} catch (err) { + if (err.name === 'ReplyError' && /WRONGTYPE|ERR /.test(err.message)) { + throw err; // Fix code or data type + } + throw err; +} +``` + +### Pattern 2: Graceful degradation + +Catch connection errors and fall back to an alternative (see +[Pattern 2: Graceful degradation]({{< relref "/develop/clients/error-handling#pattern-2-graceful-degradation" >}}) +for a full description). + +```javascript +try { + const val = await client.get(key); + if (val != null) return val; +} catch (err) { + if (['ECONNREFUSED','ECONNRESET','ETIMEDOUT','EAI_AGAIN'].includes(err.code)) { + logger.warn('Cache unavailable; falling back to DB'); + return database.get(key); + } + throw err; +} +return database.get(key); +``` + +### Pattern 3: Retry with backoff + +Retry on temporary errors like timeouts (see +[Pattern 3: Retry with backoff]({{< relref "/develop/clients/error-handling#pattern-3-retry-with-backoff" >}}) +for a full description). + +```javascript +async function getWithRetry(key, { attempts = 3, baseDelayMs = 100 } = {}) { + let delay = baseDelayMs; + for (let i = 0; i < attempts; i++) { + try { + return await client.get(key); + } catch (err) { + if ( + i < attempts - 1 && + (['ETIMEDOUT','ECONNRESET','EAI_AGAIN'].includes(err.code) || + (err.name === 'ReplyError' && /(BUSY|TRYAGAIN|LOADING)/.test(err.message))) + ) { + await new Promise(r => setTimeout(r, delay)); + delay *= 2; + continue; + } + throw err; + } + } +} +``` + +Note that you can also configure node-redis to reconnect to the +server automatically when the connection is lost. See +[Reconnect after disconnection]({{< relref "/develop/clients/nodejs/connect#reconnect-after-disconnection" >}}) +for more information. + +### Pattern 4: Log and continue + +Log non-critical errors and continue (see +[Pattern 4: Log and continue]({{< relref "/develop/clients/error-handling#pattern-4-log-and-continue" >}}) +for a full description). + +```javascript +try { + await client.setEx(key, 3600, value); +} catch (err) { + if (['ECONNREFUSED','ECONNRESET','ETIMEDOUT','EAI_AGAIN'].includes(err.code)) { + logger.warn(`Failed to cache ${key}, continuing without cache`); + } else { + throw err; + } +} +``` + +## See also + +- [Error handling]({{< relref "/develop/clients/error-handling" >}}) +- [Production usage]({{< relref "/develop/clients/nodejs/produsage" >}}) diff --git a/content/develop/clients/nodejs/migration.md b/content/develop/clients/nodejs/migration.md index f187f61853..3abfb79055 100644 --- a/content/develop/clients/nodejs/migration.md +++ b/content/develop/clients/nodejs/migration.md @@ -12,7 +12,7 @@ categories: description: Discover the differences between `ioredis` and `node-redis`. linkTitle: Migrate from ioredis title: Migrate from ioredis -weight: 6 +weight: 10 --- Redis previously recommended the [`ioredis`](https://github.com/redis/ioredis) diff --git a/content/develop/clients/nodejs/produsage.md b/content/develop/clients/nodejs/produsage.md index 74dc20f0dd..010e88ddd7 100644 --- a/content/develop/clients/nodejs/produsage.md +++ b/content/develop/clients/nodejs/produsage.md @@ -12,7 +12,7 @@ categories: description: Get your Node.js app ready for production linkTitle: Production usage title: Production usage -weight: 5 +weight: 8 --- This guide offers recommendations to get the best reliability and @@ -38,22 +38,10 @@ progress in implementing the recommendations. Node-Redis provides [multiple events to handle various scenarios](https://github.com/redis/node-redis?tab=readme-ov-file#events), among which the most critical is the `error` event. -This event is triggered whenever an error occurs within the client. - -It is crucial to listen for error events. - -If a client does not register at least one error listener and an error occurs, the system will throw that error, potentially causing the Node.js process to exit unexpectedly. -See [the EventEmitter docs](https://nodejs.org/api/events.html#events_error_events) for more details. - -```typescript -const client = createClient({ - // ... client options -}); -// Always ensure there's a listener for errors in the client to prevent process crashes due to unhandled errors -client.on('error', error => { - console.error(`Redis client error:`, error); -}); -``` +This event is triggered whenever an error occurs within the client, and +it is very important to set a handler to listen for it. +See [Error events]({{< relref "/develop/clients/nodejs/error-handling#error-events" >}}) +for more information and an example of setting an error handler. ### Handling reconnections @@ -65,7 +53,7 @@ own custom strategy. See [Reconnect after disconnection]({{< relref "/develop/clients/nodejs/connect#reconnect-after-disconnection" >}}) for more information. -### Connection timeouts +### Timeouts To set a timeout for a connection, use the `connectTimeout` option (the default timeout is 5 seconds): @@ -80,6 +68,23 @@ const client = createClient({ client.on('error', error => console.error('Redis client error:', error)); ``` +You can also set timeouts for individual commands using `AbortController`: + +```javascript +import { createClient, commandOptions } from 'redis'; + +const client = createClient({ url: 'redis://localhost:6379' }); +await client.connect(); + +const ac = new AbortController(); +const t = setTimeout(() => ac.abort(), 1000); +try { + const val = await client.get(commandOptions({ signal: ac.signal }), key); +} finally { + clearTimeout(t); +} +``` + ### Command execution reliability By default, `node-redis` reconnects automatically when the connection is lost diff --git a/content/develop/clients/redis-py/error-handling.md b/content/develop/clients/redis-py/error-handling.md new file mode 100644 index 0000000000..52b85c1cde --- /dev/null +++ b/content/develop/clients/redis-py/error-handling.md @@ -0,0 +1,137 @@ +--- +title: Error handling +description: Learn how to handle errors when using redis-py +linkTitle: Error handling +weight: 65 +--- + +redis-py uses **exceptions** to signal errors. The redis-py documentation mainly +shows the "happy path" in code examples and omits error handling for brevity. +This page explains how +redis-py's error handling works and how to apply common error handling patterns. +For an overview of error types and handling strategies, see +[Error handling]({{< relref "/develop/clients/error-handling" >}}). +See also [Production usage]({{< relref "/develop/clients/redis-py/produsage" >}}) +for more information on connection management, timeouts, and other aspects of +app reliability. + +## Exception hierarchy + +redis-py organizes exceptions in a hierarchy. The base exception is `redis.RedisError`, with specific subclasses for different error types: + +``` +RedisError (base) +├── ConnectionError +│ ├── TimeoutError +│ └── BusyLoadingError +├── ResponseError +├── InvalidResponse +├── DataError +├── PubSubError +└── ... (others) +``` + +### Key exceptions + +The following exceptions are the most commonly encountered in redis-py applications. +See +[Categories of errors]({{< relref "/develop/clients/error-handling#categories-of-errors" >}}) +for a more detailed discussion of these errors and their causes. + +| Exception | When it occurs | Recoverable | Recommended action | +|---|---|---|---| +| `redis.ConnectionError` | Network or connection issues | ✅ | Retry with backoff or fall back to alternative | +| `redis.TimeoutError` | Operation exceeded timeout | ✅ | Retry with backoff | +| `redis.ResponseError` | Invalid command or Redis error response | ❌ | Fix the command or arguments | +| `redis.DataError` | Data serialization/deserialization issues | ⚠️ | Log, invalidate cache, fetch fresh data | + +## Applying error handling patterns + +The [Error handling]({{< relref "/develop/clients/error-handling" >}}) overview +describes four main patterns. The sections below show how to implement them in +redis-py: + +### Pattern 1: Fail fast + +Catch specific exceptions that represent unrecoverable errors and re-raise them (see +[Pattern 1: Fail fast]({{< relref "/develop/clients/error-handling#pattern-1-fail-fast" >}}) +for a full description): + +```python +import redis + +r = redis.Redis() + +try: + result = r.get(key) +except redis.ResponseError: + # This indicates a bug in the code + raise +``` + +### Pattern 2: Graceful degradation + +Catch connection errors and fall back to an alternative (see +[Pattern 2: Graceful degradation]({{< relref "/develop/clients/error-handling#pattern-2-graceful-degradation" >}}) +for a full description): + +```python +try: + cached_value = r.get(key) + if cached_value: + return cached_value +except redis.ConnectionError: + logger.warning("Cache unavailable, using database") + +# Fallback to database +return database.get(key) +``` + +### Pattern 3: Retry with backoff + +Retry on temporary errors like timeouts (see +[Pattern 3: Retry with backoff]({{< relref "/develop/clients/error-handling#pattern-3-retry-with-backoff" >}}) +for a full description). redis-py has built-in retry logic +which is highly configurable. You can customize the retry strategy +(or supply your own custom strategy) and you can also specify which errors +should be retried. See +[Production usage]({{< relref "/develop/clients/redis-py/produsage#retries" >}}) +for more information. + +### Pattern 4: Log and continue + +Log non-critical errors and continue (see +[Pattern 4: Log and continue]({{< relref "/develop/clients/error-handling#pattern-4-log-and-continue" >}}) +for a full description): + +```python +try: + r.setex(key, 3600, value) +except redis.ConnectionError: + logger.warning(f"Failed to cache {key}, continuing without cache") + # Application continues normally +``` + +## Async error handling + +Error handling works the usual way when you use `async`/`await`, +as shown in the example below: + +```python +import redis.asyncio as redis + +async def get_with_fallback(key): + r = await redis.from_url("redis://localhost") + try: + return await r.get(key) + except redis.ConnectionError: + logger.warning("Cache unavailable") + return await database.get(key) + finally: + await r.close() +``` + +## See also + +- [Error handling]({{< relref "/develop/clients/error-handling" >}}) +- [Production usage]({{< relref "/develop/clients/redis-py/produsage" >}}) diff --git a/layouts/_default/_markup/render-codeblock-mermaid.html b/layouts/_default/_markup/render-codeblock-mermaid.html new file mode 100644 index 0000000000..9915805e2b --- /dev/null +++ b/layouts/_default/_markup/render-codeblock-mermaid.html @@ -0,0 +1,7 @@ +{{ $width := (index .Attributes "width") | default "75%" }} +
+
+    {{ .Inner | htmlEscape | safeHTML }}
+
+
+{{ .Page.Store.Set "hasMermaid" true }} diff --git a/layouts/_default/baseof.html b/layouts/_default/baseof.html index bce33e0547..fac415cc8f 100644 --- a/layouts/_default/baseof.html +++ b/layouts/_default/baseof.html @@ -80,6 +80,21 @@ {{ partial "search-modal.html" . }} + {{ if .Store.Get "hasMermaid" }} + + {{ end }} + {{ if .Page.Store.Get "hasChecklist" }}