astral-sh / astral-sh/ruff

TRY400 flags log.error() + raise/sys.exit()

Open
#4,136 14 comments 4 reactions 0 assignees View on GitHub
needs-decision rule
Dominant language
Rust
Stars
49.6k
Forks
2.4k
Avg merge
2d 1h
Merged PRs (30d)
445

Description

In the following code snippet, a TRY400 violation is raised because I use log.error() and not log.exception() in an exception handler. In this case it's by design as I immediately re-raise the exception, I just want to add some message to the exception and I don't want the stacktrace shown twice.

```
import logging
log = logging.get_logger(__name__)
# The outer app loop...
try:
# actually some function call which can't handle the error but wants to abort...
try:
raise Exception("bad")
except Exception:
# to get some info into the log to "enrich" it...
# and I don't want to see the exception stacktrace twice
log.error("That might mean ..." ) # noqa: TRY400: use log.exception()
raise
except Exception:
log.exception("Caught unhandled exception in outer context")
```

In my opinion the pattern "in except block, with a log.something + 'raise' in all cases` should be something TRY400 should ignore/be ok with.

Contributor guide

Open the contributing guide

Research direction

Search Ruff's TRY400 implementation and its existing tests; start by tracing how an exception handler containing logging followed by raise or sys.exit is classified. Done means the described log-and-re-raise pattern is accepted without suppressing other TRY400 violations, with tests covering the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.