Example result: Improve error handling in your code
AI-generated example · Error Handling
Updated

Improve error handling in your code

This prompt finds errors that are hidden, caught too broadly or shown to users with internal details, plus risky calls with no handling at all. It rewrites the code with clear error handling for where your code runs.

text-code-error-handling-review — claude — 77 words

Act as a senior [LANGUAGE] engineer focused on reliability.

Code:
[PASTE]

This code runs in [CONTEXT, e.g. a payment webhook handler]. Find places where errors are swallowed, caught too broadly, logged without context, or shown to users with internal details. Also find places with no error handling that need it (network calls, file access, parsing, database writes). Rewrite the code with clear error handling, useful log messages and safe user-facing messages. Explain each change in one line.

Tell it where the code runs. A CLI script, a web API and a background job each need different error handling.

Get a better result

What you will get

Your code rewritten with clear error handling: swallowed and over broad catches fixed, network, file, parsing and database calls guarded, useful log messages added and safe messages for users, with each change explained in a line.

Why it works

The context line is what makes this work, as the tip says: a web API should return a clean error, a background job should retry, and a CLI should exit with a clear message. Listing the usual failure points keeps it from skipping the network call that breaks first. One line per change lets you review the reasoning, not just the new code.

Common mistake

Every error is caught and logged, then ignored.

Fix: Ask it to decide for each error whether to retry, fail the request or stop the job, and to explain the choice.

Also watch for
  • Logs now include passwords or card details. Ask it to list exactly what each log line records and to remove personal data and secrets.
  • Retries run forever on a webhook. Ask for a retry limit with a delay, and for the handler to be safe if the same event arrives twice.
Try a variation: add error tracking

Ask where to report errors to a tracking service, with the request ID attached, and which errors are too routine to report.

Still not right? Reply with this

Write one test for each new error path, checking the status code, the log message and what the user sees.

More chat & writing prompts

See all 465 →