Skip to main content
rule CX Codex

exception-logging — Claude Code rule: what it does, how to install

exception-logging — a rule for Claude Code that enforces Java exception handling and logging standards. Runs during code review to catch empty catch blocks, unmasked data, and missing transaction rollbacks.

MIT ★ 517 updated 2026-11-16

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/exception-logging.md
Open on GitHub

What exception-logging does

The rule enforces semantic standards for Java error handling and log formatting. It flags empty catch blocks, return statements inside finally blocks, and raw NullPointerException catches when null pre-checks should be used instead. For chained method calls, it requires wrapping access in Optional.

In methods marked with @Transactional, catching an exception mandates calling TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(). The rule forces logging through the SLF4J facade instead of direct Log4j or Logback classes, prohibits string concatenation in log calls in favor of {} placeholders, and requires data masking helpers for phone numbers and IDs. In logback.xml, it verifies additivity="false" to prevent duplicate appender entries.

Projects without an SLF4J binding or masking utilities will fail the rule checks on direct logger calls.

What it helps with

  • eliminate empty catch blocks and swallowed exceptions
  • enforce manual transaction rollbacks inside catch blocks
  • replace direct Log4j imports with the SLF4J facade
  • mask sensitive user data before writing to logs
  • replace chained null checks with Optional mapping

Example prompts for the agent

  • Review UserService.java against exception-logging standards
  • Refactor error handling in updateUser to include transaction rollback
  • Replace string concatenation in logger calls with SLF4J placeholders

How to install exception-logging

Manually: put the files in place

.claude/rules/exception-logging.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about exception-logging

How to install exception-logging in Claude Code?

Add the rule file to your project repository at .claude/rules/exception-logging.md.

What logging practices does this rule enforce?

It mandates the SLF4J API, parameter substitution using {} syntax, stack trace inclusion on error logs, and explicit masking of sensitive fields.

What does the rule require for transactional methods?

When catching exceptions inside @Transactional methods, you must invoke TransactionAspectSupport.currentTransactionStatus().setRollbackOnly() before throwing a business exception.

Source text

exception-logging.md · MIT
# Exception handling and logging guidelines

## Exception handling

### Exception catching
**Detection mode**: semantic

**Empty catch blocks are forbidden (MULT-EXC-001):**

```java
// Wrong: swallows the exception
try {
    doSomething();
} catch (Exception e) {
    // empty block
}

// Correct: at least log it
try {
    doSomething();
} catch (Exception e) {
    log.error("Failed to do something", e);
    throw new BusinessException("operation failed", e);
}
```

### Transaction rollback
**Detection mode**: semantic

**Catching an exception in transactional code requires a manual rollback (MULT-EXC-002):**

```java
@Transactional(rollbackFor = Exception.class)
public void updateUser(User user) {
    try {
        userDao.update(user);
        userPhoneDao.update(user.getPhone());
    } catch (Exception e) {
        log.error("failed to update user", e);
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        throw new BusinessException("update failed");
    }
}
```

### finally rules
**Detection mode**: semantic

**Do not return from finally (MULT-EXC-003):**

```java
// Wrong
try {
    return 1;
} finally {
    return 2;  // Forbidden! Overrides the return in try
}

// Correct
try {
    return 1;
} finally {
    // Cleanup is allowed here, but no return
}
```

### Resource cleanup
**Detection mode**: semantic

**The finally block must close resources; on JDK 7+ use try-with-resources (MULT-EXC-004):**

```java
// Correct
try (InputStream is = new FileInputStream(file);
     OutputStream os = new FileOutputStream(output)) {
    // use the resource
} catch (IOException e) {
    log.error("IO error", e);
}
```

### Pre-check principle
**Detection mode**: semantic

**Pre-checks are better than exception catching (MULT-EXC-005):**

```java
// Wrong
try {
    return user.getName().toUpperCase();
} catch (NullPointerException e) {
    return null;
}

// Correct
if (user != null && user.getName() != null) {
    return user.getName().toUpperCase();
}
return null;
```

### Exception classification
**Detection mode**: semantic

**Distinguish stable code from unstable code (MULT-EXC-007):**

```java
// Stable code: catch a specific exception
try {
    userDao.insert(user);
} catch (DuplicateKeyException e) {
    log.warn("Duplicate user: {}", user.getId());
    throw new BusinessException("user already exists");
}

// Unstable code: catch a broader exception
try {
    thirdPartyService.call();
} catch (Exception e) {
    log.error("Third party call failed", e);
    throw new ServiceException("third-party service call failed", e);
}
```

### Cascading-call NPEs
**Detection mode**: semantic

**Cascading calls are prone to NPEs; use Optional (MULT-EXC-008):**

```java
// Wrong
String cityName = user.getAddress().getCity().getName();

// Correct
String cityName = Optional.ofNullable(user)
    .map(User::getAddress)
    .map(Address::getCity)
    .map(City::getName)
    .orElse("unknown");
```

## Logging

### Logging framework
**Detection mode**: semantic

**Depend on the SLF4J facade; do not use Log4j/Logback APIs directly (MULT-LOG-140):**

```java
// Wrong: use Log4j/Logback directly
import org.apache.log4j.Logger;

// Correct: use SLF4J
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger log = LoggerFactory.getLogger(UserService.class);
```

### Log content
**Detection mode**: semantic

**Exception logs must include context and the stack trace (MULT-LOG-141):**

```java
// Correct
log.error("params: {}, error: {}", userId, e.getMessage(), e);

// Or use placeholders
log.error("failed to update user, userId={}, error={}", userId, e.getMessage(), e);
```

### Conditional output
**Detection mode**: semantic

**Use conditional output or placeholders for trace/debug/info (MULT-LOG-142):**

```java
// Wrong: string concatenation
log.debug("Processing user: " + userId);

// Correct: placeholder
log.debug("Processing user: {}", userId);

// Or conditional output
if (log.isDebugEnabled()) {
    log.debug("Processing user: {}", userId);
}
```

### Sensitive-data masking
**Detection mode**: semantic

**Logs must be masked (MULT-SEC-025/026):**

```java
// Wrong: log sensitive information directly
log.info("User login: phone={}, idCard={}", phone, idCard);

// Correct: mask it
log.info("User login: phone={}, idCard={}", 
    SensitiveDataMasker.maskPhone(phone), 
    SensitiveDataMasker.maskIdCard(idCard));

// Or use the masking helper
log.info("User login: {}", SensitiveDataMasker.maskUserInfo(user));
```

### Log levels
**Detection mode**: semantic

**Disable debug in production; enable info selectively (MULT-LOG-146):**

```java
// Wrong
log.debug("Detailed info");

// Correct
log.info("Operation info");
log.warn("Warning info");
log.error("Error info", e);
```

### Duplicate logs
**Detection mode**: semantic

**Avoid duplicate log output; set additivity=false (MULT-LOG-143):**

```xml
<!-- logback.xml -->
<logger name="com.example.service" level="INFO" additivity="false">
    <appender-ref ref="FILE"/>
</logger>
```

© kyy-logs · MIT · kyy-logs/code-review-gate-skill

Similar IDE rules

All IDE rules for Code review and refactoring →

From the same set10

The whole set →
baseline-java The baseline-java Claude Code rule adds Java checks for security, concurrency, and exception handling. It applies during Java code review. CX Codex +1 ★ 517repo stars spring-performance spring-performance is a Claude Code rule for Spring/JPA practices and performance tuning. It guides agents working on Java code, database queries, and server settings. CX Codex +1 ★ 517repo stars spring-performance The spring-performance Claude Code rule sets Spring/JPA and performance checks. It flags issues in validation, transactions, queries, and batch operations. CX Codex +1 ★ 517repo stars concurrency This Claude Code rule sets Java concurrency guidelines. It covers thread pools, locks, shared records, and other sources of concurrent access bugs. CX Codex +1 ★ 517repo stars naming-format The naming-format Claude Code rule sets Java naming and formatting conventions. It covers classes, methods, constants, and control flow. CX Codex +1 ★ 517repo stars testing-engineering The testing-engineering Claude Code rule sets expectations for unit tests, project structure, and dependencies. It covers application layers, exception handling, and domain models. CX Codex +1 ★ 517repo stars code-review-gate The code-review-gate Claude Code skill reviews code changes before a commit or PR merge. It gathers the diff, checks test quality, and records issues. CX Codex +1 ★ 517repo stars oop-collection The oop-collection Claude Code rule sets guidelines for Java objects and collections. It covers null checks, object comparisons, and safe list updates. CX Codex +1 ★ 517repo stars

Project sponsors

Companies that keep this analytics open