Custom errors

suggest change

PHP signals errors by throwing objects that implement Throwable. The built-in classes (RuntimeException, InvalidArgumentException, JsonException and so on) are generic. When your own code fails in a way callers should handle differently, define your own exception class.

A custom exception lets you:

The basics of try / catch are covered in Exception and Error handling, and cleanup with finally in try, finally, and cleanup.

The simplest custom exception

A custom exception is a class that extends Exception or one of its subclasses. Often the body is empty, because all you need is a new type:

<?php
class InsufficientFundsException extends RuntimeException {}

function withdraw(int $balance, int $amount): int
{
    if ($amount > $balance) {
        throw new InsufficientFundsException(
            "cannot withdraw $amount, balance is $balance"
        );
    }
    return $balance - $amount;
}

try {
    echo withdraw(100, 30), "\n";
    echo withdraw(100, 250), "\n";
} catch (InsufficientFundsException $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

$e = new InsufficientFundsException('x');
var_dump($e instanceof RuntimeException);
var_dump($e instanceof Exception);
var_dump($e instanceof Throwable);

Output:

70
InsufficientFundsException: cannot withdraw 250, balance is 100
bool(true)
bool(true)
bool(true)

The class inherits everything from Exception: the constructor ($message, $code, $previous), getMessage(), getCode(), getFile(), getLine(), getTrace() and getPrevious(). File and line are recorded where the object is created with new, not where it is thrown.

Which class to extend

Extend the most specific built-in class that describes the failure. Code that catches the parent class will then catch yours too.

PHP's exception hierarchy:

Throwable (interface)
├── Error                        engine errors: TypeError, ValueError, ArithmeticError, ...
└── Exception
    ├── LogicException           bug in the calling code, fix the code
    │   ├── BadFunctionCallException
    │   │   └── BadMethodCallException
    │   ├── DomainException
    │   ├── InvalidArgumentException
    │   ├── LengthException
    │   └── OutOfRangeException
    ├── RuntimeException         failure only detectable at run time
    │   ├── OutOfBoundsException
    │   ├── OverflowException
    │   ├── RangeException
    │   ├── UnderflowException
    │   └── UnexpectedValueException
    ├── JsonException, PDOException, ...

Rules of thumb:

You can't implement Throwable directly. Only classes that extend Exception or Error can be thrown:

<?php
class Foo implements Throwable {}

Output:

Fatal error: Class Foo cannot implement interface Throwable, extend Exception or Error instead in ... on line 2

Adding data to an exception

A message string is for humans. If a caller needs to make decisions based on details of the error, put those details in properties. Constructor property promotion with readonly makes this short:

<?php
class InsufficientFundsException extends RuntimeException
{
    public function __construct(
        public readonly int $balance,
        public readonly int $requested,
        ?Throwable $previous = null,
    ) {
        $shortfall = $requested - $balance;
        parent::__construct(
            "insufficient funds: requested $requested, balance $balance, short by $shortfall",
            0,
            $previous,
        );
    }

    public function shortfall(): int
    {
        return $this->requested - $this->balance;
    }
}

try {
    throw new InsufficientFundsException(balance: 100, requested: 250);
} catch (InsufficientFundsException $e) {
    echo $e->getMessage(), "\n";
    echo "balance:   ", $e->balance, "\n";
    echo "requested: ", $e->requested, "\n";
    echo "shortfall: ", $e->shortfall(), "\n";
    echo "line:      ", $e->getLine(), "\n";
}

Output:

insufficient funds: requested 250, balance 100, short by 150
balance:   100
requested: 250
shortfall: 150
line:      24

Things to keep in mind when you write a constructor:

Exception methods are final

getMessage(), getCode(), getFile(), getLine(), getTrace(), getPrevious() and getTraceAsString() are final. You can't override them:

<?php
class MyException extends Exception
{
    public function getMessage(): string
    {
        return 'custom';
    }
}

Output:

Fatal error: Cannot override final method Exception::getMessage() in ... on line 4

Set the message through the constructor instead. The only methods you can override are the constructor and __toString().

Named constructors

When the same exception can be thrown for several reasons, static factory methods give each reason a name and keep message formatting in one place:

<?php
final class UserNotFound extends RuntimeException
{
    private function __construct(string $message, public readonly array $criteria)
    {
        parent::__construct($message);
    }

    public static function withId(int $id): self
    {
        return new self("user with id $id not found", ['id' => $id]);
    }

    public static function withEmail(string $email): self
    {
        return new self("user with email '$email' not found", ['email' => $email]);
    }
}

function findUser(array $criteria): never
{
    throw isset($criteria['id'])
        ? UserNotFound::withId($criteria['id'])
        : UserNotFound::withEmail($criteria['email']);
}

foreach ([['id' => 42], ['email' => 'bob@example.com']] as $c) {
    try {
        findUser($c);
    } catch (UserNotFound $e) {
        echo $e->getMessage(), " (line ", $e->getLine(), ")\n";
        echo "  criteria: ", json_encode($e->criteria), "\n";
    }
}

Output:

user with id 42 not found (line 11)
  criteria: {"id":42}
user with email 'bob@example.com' not found (line 16)
  criteria: {"email":"bob@example.com"}

Call sites read well: throw UserNotFound::withId($id).

Notice the line numbers: 11 and 16 are inside the factory methods, because that's where new runs. The stack trace (getTrace()) still shows the real call site, but if you log only file and line, keep that in mind.

A hierarchy for a library

A library or module should let callers catch "any error from this library" with one catch. The common way to do that is a marker interface that extends Throwable. Each concrete exception extends the most fitting SPL class and implements the interface:

<?php
namespace Acme\Payments;

// marker interface: every exception thrown by this library implements it
interface PaymentException extends \Throwable {}

class InvalidAmount extends \InvalidArgumentException implements PaymentException {}
class CardDeclined extends \RuntimeException implements PaymentException {}
class GatewayUnavailable extends \RuntimeException implements PaymentException {}

function charge(int $cents, string $card): string
{
    if ($cents <= 0) {
        throw new InvalidAmount("amount must be positive, got $cents");
    }
    if (str_starts_with($card, '0000')) {
        throw new CardDeclined("card ending in " . substr($card, -4) . " was declined");
    }
    if ($card === 'offline') {
        throw new GatewayUnavailable('payment gateway timed out');
    }
    return "charged $cents cents";
}

$cases = [[500, '4242424242424242'], [-5, '4242'], [500, '0000111122223333'], [500, 'offline']];
foreach ($cases as [$cents, $card]) {
    try {
        echo charge($cents, $card), "\n";
    } catch (CardDeclined $e) {
        echo "ask for another card: ", $e->getMessage(), "\n";
    } catch (InvalidAmount | GatewayUnavailable $e) {
        echo "specific: ", (new \ReflectionClass($e))->getShortName(), "\n";
    }
}

// a caller that doesn't care about details catches the interface
try {
    charge(500, 'offline');
} catch (PaymentException $e) {
    echo "payment failed: ", $e->getMessage(), "\n";
}

$e = new InvalidAmount('x');
var_dump($e instanceof \InvalidArgumentException, $e instanceof PaymentException);

Output:

charged 500 cents
specific: InvalidAmount
ask for another card: card ending in 3333 was declined
specific: GatewayUnavailable
payment failed: payment gateway timed out
bool(true)
bool(true)

Why an interface rather than a common base class? PHP has single inheritance. A base class PaymentException extends RuntimeException would force every exception to be a RuntimeException, and InvalidAmount could no longer be an InvalidArgumentException. With an interface, code that catches \InvalidArgumentException and code that catches PaymentException both work. This is the pattern used by Guzzle, Symfony components, PSR-18 (Psr\Http\Client\ClientExceptionInterface) and many other libraries.

Catch order matters: PHP uses the first catch block that matches, so list specific classes before general ones.

When you use namespaces, remember the leading backslash on built-in classes (\RuntimeException), or PHP will look for Acme\Payments\RuntimeException.

Wrapping lower-level exceptions

A function should throw errors that make sense at its own level of abstraction. A loadConfig() caller wants to know "the config couldn't be loaded", not whether that was due to a JsonException or a missing file. Catch the low-level exception and throw your own, passing the original as $previous:

<?php
class ConfigException extends RuntimeException
{
    public static function unreadable(string $path, Throwable $previous): self
    {
        return new self("cannot load config from $path", 0, $previous);
    }
}

function loadConfig(string $path): array
{
    try {
        $json = file_get_contents($path)
            ?: throw new RuntimeException("file $path is missing or empty");
        return json_decode($json, true, flags: JSON_THROW_ON_ERROR);
    } catch (JsonException | RuntimeException $e) {
        throw ConfigException::unreadable($path, $e);
    }
}

file_put_contents('app.json', '{"debug": tru');

try {
    loadConfig('app.json');
} catch (ConfigException $e) {
    $level = 0;
    for ($cur = $e; $cur !== null; $cur = $cur->getPrevious()) {
        printf("%s%s: %s\n", str_repeat('  ', $level++), $cur::class, $cur->getMessage());
    }
}

Output:

ConfigException: cannot load config from app.json
  JsonException: Syntax error

Never drop the original exception. Without $previous the root cause, including its stack trace, is gone, and debugging gets much harder.

If a chained exception isn't caught, PHP prints the whole chain, starting with the innermost exception, with each further one introduced by Next:

<?php
class StorageException extends RuntimeException {}

function save(): void
{
    try {
        throw new PDOException('SQLSTATE[HY000]: database is locked');
    } catch (PDOException $e) {
        throw new StorageException('could not save order', previous: $e);
    }
}

save();

Output (paths shortened):

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: database is locked in /app/save.php:7
Stack trace:
#0 /app/save.php(13): save()
#1 {main}

Next StorageException: could not save order in /app/save.php:9
Stack trace:
#0 /app/save.php(13): save()
#1 {main}
  thrown in /app/save.php on line 9

Named arguments (previous: $e) let you skip the $code argument you don't care about.

Error codes with enums

The built-in $code is an int, which is fine for HTTP statuses or errno values but not very descriptive. For a fixed set of error kinds, a backed enum carried in a property works better. It's type-safe, can be matched exhaustively, and can carry behavior:

<?php
enum OrderError: string
{
    case OutOfStock = 'out_of_stock';
    case InvalidCoupon = 'invalid_coupon';
    case AddressRequired = 'address_required';

    public function httpStatus(): int
    {
        return match ($this) {
            self::OutOfStock => 409,
            self::InvalidCoupon, self::AddressRequired => 422,
        };
    }
}

final class OrderException extends DomainException
{
    public function __construct(
        public readonly OrderError $error,
        string $message,
        public readonly array $context = [],
    ) {
        parent::__construct($message);
    }
}

function placeOrder(array $order): void
{
    if (empty($order['address'])) {
        throw new OrderException(OrderError::AddressRequired, 'shipping address is required');
    }
    if ($order['qty'] > 3) {
        throw new OrderException(
            OrderError::OutOfStock,
            "only 3 items left",
            ['sku' => $order['sku'], 'requested' => $order['qty'], 'available' => 3],
        );
    }
    echo "order placed\n";
}

$orders = [
    ['sku' => 'A1', 'qty' => 1, 'address' => 'Main St 1'],
    ['sku' => 'A1', 'qty' => 1, 'address' => ''],
    ['sku' => 'A1', 'qty' => 5, 'address' => 'Main St 1'],
];
foreach ($orders as $order) {
    try {
        placeOrder($order);
    } catch (OrderException $e) {
        $body = ['error' => $e->error->value, 'message' => $e->getMessage()] + $e->context;
        echo $e->error->httpStatus(), ' ', json_encode($body), "\n";
    }
}

Output:

order placed
422 {"error":"address_required","message":"shipping address is required"}
409 {"error":"out_of_stock","message":"only 3 items left","sku":"A1","requested":5,"available":3}

One exception class with an enum is a good choice when callers usually handle all the cases the same way and only sometimes look at the kind. If callers routinely catch individual cases, separate classes are cleaner.

Safe messages for users

Exception messages often contain internal details: SQL, file paths, sometimes secrets. A web application should show the user only messages that are meant for them. One way is an interface that marks "this exception is safe to show" and carries the response details:

<?php
// Exceptions whose message is safe to show to end users
interface UserFacing extends Throwable
{
    public function publicMessage(): string;
    public function httpStatus(): int;
}

class NotFound extends RuntimeException implements UserFacing
{
    public function publicMessage(): string { return $this->getMessage(); }
    public function httpStatus(): int { return 404; }
}

class ValidationFailed extends InvalidArgumentException implements UserFacing
{
    /** @param array<string, string> $errors field => message */
    public function __construct(public readonly array $errors)
    {
        parent::__construct('validation failed: ' . implode(', ', array_keys($errors)));
    }
    public function publicMessage(): string { return 'invalid input'; }
    public function httpStatus(): int { return 422; }
}

function handle(callable $action): void
{
    try {
        $action();
        echo "200 OK\n";
    } catch (UserFacing $e) {
        $body = ['error' => $e->publicMessage()];
        if ($e instanceof ValidationFailed) {
            $body['fields'] = $e->errors;
        }
        echo $e->httpStatus(), ' ', json_encode($body), "\n";
    } catch (Throwable $e) {
        // internal details go to the log, never to the client
        error_log(sprintf('%s: %s at %s:%d', $e::class, $e->getMessage(), basename($e->getFile()), $e->getLine()));
        echo "500 ", json_encode(['error' => 'internal server error']), "\n";
    }
}

ini_set('error_log', 'php://stdout');

handle(fn() => null);
handle(fn() => throw new NotFound('article 17 does not exist'));
handle(fn() => throw new ValidationFailed(['email' => 'is not a valid email', 'age' => 'must be 18 or older']));
handle(fn() => throw new LogicException('db password is hunter2'));

Output:

200 OK
404 {"error":"article 17 does not exist"}
422 {"error":"invalid input","fields":{"email":"is not a valid email","age":"must be 18 or older"}}
LogicException: db password is hunter2 at app.php:49
500 {"error":"internal server error"}

In a real application the handle() logic lives in a front controller, a middleware or a handler registered with set_exception_handler(). Anything that isn't explicitly marked UserFacing becomes a generic 500.

Customizing __toString()

Converting an exception to a string (echo $e, (string) $e, string interpolation) calls __toString(). The default prints the class, message, file, line and full stack trace. You can override it, for example to produce a compact one-line form for logs:

<?php
class HttpRequestFailed extends RuntimeException
{
    public function __construct(
        public readonly string $method,
        public readonly string $url,
        public readonly int $status,
    ) {
        parent::__construct("$method $url returned HTTP $status", $status);
    }

    public function __toString(): string
    {
        return sprintf('%s [%s %s -> %d] at line %d', static::class,
            $this->method, $this->url, $this->status, $this->getLine());
    }
}

$e = new HttpRequestFailed('GET', 'https://api.example.com/users/7', 503);
echo $e, "\n";
echo $e->getMessage(), "\n";
echo $e->getCode(), "\n";

Output:

HttpRequestFailed [GET https://api.example.com/users/7 -> 503] at line 19
GET https://api.example.com/users/7 returned HTTP 503
503

Overriding __toString() drops the stack trace from the string form, so do it only if your logger records the trace separately (most do, via getTrace()). The uncaught-exception message PHP prints is not affected.

When to create a custom exception

Not every throw needs a new class. Create one when:

A built-in class is fine when nobody will catch the error specifically. For an invalid argument, throw new InvalidArgumentException(...) is clear enough.

To check that code throws the right custom exception in tests, see Test exceptions.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents