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
.claude/rules/exception-logging.mdWhat 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.javaagainst exception-logging standards - Refactor error handling in
updateUserto 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.mdThe paths frontmatter field limits the files
AGENTS.md
Codex reads AGENTS.md: paste the rule text there
Manually: put the files in place
.cursor/rules/exception-logging.mdcFrontmatter: description, globs, alwaysApply
Manually: put the files in place
.github/instructions/exception-logging.instructions.mdThe applyTo field sets which files it applies to
Manually: put the files in place
.devin/rules/exception-logging.mdManually: put the files in place
.clinerules/exception-logging.mdStep 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