agentleFS
AnyOrgNameAnyOrgName/php-skills/skills/php/error-handling/SKILL.md

error-handling

Skill4 starsChanged 4 months agoMITView on GitHub

Handle failures with exceptions in PHP 8.0+ — custom exception hierarchies, catching by type, try/finally cleanup, chaining, and the never return type. Use when the user must release a resource (file handle, lock, transaction) whether or not an exception is thrown on PHP 8.0+; the user needs domain-specific exceptions that callers can catch selectively on PHP 8.0+; the user wants to catch a low-level exception (PDO, cURL) and rethrow it as a domain exception without losing the cause on PHP 8.0+. Keywords: error-handling, exceptions, php80, never-type, try-finally.

80 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use convention-learner, caching and 9 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • codewithmukeshSkill

    convention-learner

    Detects and enforces project-specific coding conventions by analyzing existing codebase patterns. Learns naming conventions, folder structure, test organization, and coding style from the existing code. Load when: "conventions", "coding standards", "project patterns", "enforce style", "detect patterns", "learn conventions", "code consistency".

    Also in 3 projects that use this

  • wpankSkill

    caching

    Caching strategies, invalidation, eviction policies, HTTP caching, distributed caching, and anti-patterns. Use when designing cache layers, choosing eviction policies, debugging stale data, or optimizing read-heavy workloads.

    Also in 6 projects that use this

  • diego-tobalinaSkill

    logging

    Logging best practices for Java (SLF4J/Logback) and Node.js (Winston/Pino). Use for structured logging, log levels, and avoiding sensitive data exposure.

    Also in 12 projects that use this

  • codewithmukeshSkill

    opentelemetry

    OpenTelemetry observability for .NET 10 applications. Covers traces, metrics, and logs using the OpenTelemetry SDK with OTLP export. Includes custom ActivitySource, IMeterFactory metrics, resource configuration, and Aspire Dashboard integration. Load this skill when setting up distributed tracing, custom metrics, OTLP export, or when the user mentions "OpenTelemetry", "OTLP", "traces", "spans", "Activity", "ActivitySource", "metrics", "IMeterFactory", "Meter", "Counter", "Histogram", "Gauge", "telemetry", "observability", "distributed tracing", "OTEL", or "Aspire Dashboard".

    Also in 3 projects that use this

  • MovGP0Skill

    modern-csharp

    Modern C# style guidance for Bendex and MicroSea code changes, including primary constructors, expression-bodied members, var usage, target-typed new, lambdas, and pattern matching.

    Also in 3 projects that use this

  • MicrosoftSkill

    resilience

    Apply resilience patterns (retry, backoff, circuit breaking) when writing or reviewing code that makes outbound HTTP/REST calls, database operations, or any I/O that can experience transient failures. Use this skill when: (1) writing new code that calls external services or APIs, (2) reviewing code that uses fetch, HTTP clients, or service-to-service calls, (3) adding queue consumers or workers that interact with remote systems, (4) debugging intermittent failures in production.

    Also in 4 projects that use this

The file

We split this skill into the rules it gives an agent

3 rules. 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 64 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not use this skill for ordinary control flow where a missing or absent value is an expected outcome, not a failure.

    line 64
  2. Very specific:

    Do not use this skill when the intent is to suppress errors with @ or an empty catch to make a symptom disappear.

    line 65
  3. Very specific:

    When rethrowing, pass the caught exception as the third $previous constructor argument (throw new OrderException('...', 0, $e);) rather …

    line 87

“Common” is measured: kept by at least 6 in 10 of the 64 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- generated: do not edit — source: knowledge/atoms/php/error-handling/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->

PHP Error Handling

When to use

  • The user must release a resource (file handle, lock, transaction) whether or not an exception is thrown on PHP 8.0+.
  • The user needs domain-specific exceptions that callers can catch selectively on PHP 8.0+.
  • The user wants to catch a low-level exception (PDO, cURL) and rethrow it as a domain exception without losing the cause on PHP 8.0+.

When NOT to use

  • Do not use this skill for ordinary control flow where a missing or absent value is an expected outcome, not a failure.
  • Do not use this skill when the intent is to suppress errors with @ or an empty catch to make a symptom disappear.

Core guidance

  • Catch the most specific exception type — Catch the narrowest exception type that you can actually handle (catch (PaymentDeclinedException $e)), not a blanket catch (\Throwable $e).
  • Root the hierarchy in a marker base exception — Give each bounded context one base exception (abstract class OrderException extends \RuntimeException) and extend it for specific failures.
  • Release resources in finally, not in each path — Put resource release (close handle, unlock, roll back) in a finally block so it runs once on both the success and exception paths.

Quick recipe

  1. Declare one abstract or concrete base exception per bounded context extending an SPL type (class OrderException extends \RuntimeException). (verify: Callers can catch (OrderException $e) for any order-domain failure)
  2. Extend the base for each distinct failure and add static named constructors (PaymentDeclined::forOrder($id)) that build a rich message. (verify: Each failure type is catchable on its own and carries context in its message)
  3. At integration boundaries, catch the low-level exception and rethrow the domain type passing the original as $previous; catch the domain base at the top-level handler. (verify: Logs show the domain exception with the original cause preserved via getPrevious())

Best practices

  • When rethrowing, pass the caught exception as the third $previous constructor argument (throw new OrderException('...', 0, $e);) rather than discarding it
  • Give a function that always throws or exits the never return type (function fail(string $m): never) so callers and analyzers know it does not return

Anti-patterns

Anti-patternWhy it failsDo instead
Catching Throwable everywhereBlanket catches hide programming errors, defeat fail-fast behavior, and turn every bug into a swallowed no-op.Catch specific, recoverable exception types locally and let one top-level handler<br>(framework exception handler) deal with the unexpected \Throwable.
Silencing with the @ operatorThe @ operator suppresses the diagnostic but not the underlying problem, and it<br>disables logging so the failure vanishes.Fix the condition that triggers the warning, guard with a check, or catch the<br>exception the operation throws; never mask it with @.
Using exceptions for normal control flowExceptions are costly and obscure intent when used for expected branches; they should signal genuinely exceptional states.Return a nullable value, an Option/Result type, or a boolean for expected outcomes and reserve exceptions for real failures.

See references/anti-patterns.md.

Common mistakes

  1. catch(Exception) misses Error types — catch (\Exception $e) does not catch \Error subtypes (TypeError, UnhandledMatchError), because both extend \Throwable, not \Exception. Fix: Catch \Throwable at a top-level boundary when you genuinely must handle both exceptions and errors; otherwise catch the specific exception types you can recover from.
  2. Rethrowing without the previous exception — Catching a low-level error and throwing a new one without passing $previous drops the original stack trace and root cause. Fix: Always pass the caught exception as the third constructor argument (throw new DomainException('...', 0, $e);) so getPrevious() retains the cause.
  3. Empty catch block silently swallows failures — A catch (\Throwable $e) {} with an empty body discards the error and lets execution continue as if nothing failed. Fix: Handle, log, or rethrow the exception; if catching truly is intentional (e.g. optional cache warm-up), log at minimum and document why it is safe to ignore.

Version notes

  • never return type added in PHP 8.1 (PHP >=8.1) — The never return type, for functions that always throw or exit, is available from PHP 8.1; on 8.0 and earlier express the intent only with a @return never docblock.

Security

  • Do not leak exception details to clients — Never render raw exception messages, stack traces, SQL, or file paths to end users; log the full detail server-side and return a generic message with a correlation id.

Testing

  • Activation and decision behavior are verified in eval/scenarios/php/error-handling.yaml.

Additional resources

  • references/anti-patterns.md
  • references/core.md
  • references/examples.md
  • references/pitfalls.md
  • references/recipes.md
  • references/version-differences.md

Knowledge graph

Related: php/enums, php/match-expression

<!-- graph-fragment: graph/fragments/php/error-handling.yaml -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.