Skip to Content
Course content

119: Custom Exception Classes Revisited

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time in code reviews: a developer creates a dozen different exception classes, but every single one of them is just an empty class that extends \Exception. They'll have a UserNotFoundException, a DatabaseConnectionException, and a InvalidInputException, but none of them actually do anything different from the base exception.

Custom Exceptions are just for better naming

The misconception here is that the primary purpose of a custom exception is to give the error a descriptive name so the logs look prettier. If that's all you're doing, you're essentially just creating "tags" for your errors. While that's not technically wrong, it's a waste of your time and adds unnecessary boilerplate to your project. Look at this:

// This is basically useless
class OrderNotFoundException extends \Exception {}

// Later in the code...
throw new OrderNotFoundException("Order #123 not found");

If your only reaction to this exception is to catch it and display the message to the user, you didn't need a custom class. A standard \Exception or a \RuntimeException would have behaved exactly the same way. You've added a file to your project without adding any actual functionality.

Exceptions as Data Carriers for Recovery Logic

The real power of custom exceptions kicks in when you treat them as data objects. An exception shouldn't just tell you that something went wrong; it should provide the necessary context for the catch block to actually fix the problem or make an informed decision about what to do next.

Let's imagine we're building a payment integration. If a payment fails, "Payment failed" is a useless message for a programmer. Did it fail because the card expired? Because there were insufficient funds? Or because the API is down? Each of those requires a different response from the application.

class PaymentFailedException extends \Exception 
{
    private string $gatewayErrorCode;
    private bool $isRetryable;

    public function __construct(string $message, string $gatewayErrorCode, bool $isRetryable) 
    {
        parent::__construct($message);
        $this->gatewayErrorCode = $gatewayErrorCode;
        $this->isRetryable = $isRetryable;
    }

    public function getGatewayErrorCode(): string 
    {
        return $this->gatewayErrorCode;
    }

    public function shouldRetry(): bool 
    {
        return $this->isRetryable;
    }
}

Now, look at how this changes your handling logic. You aren't just catching a "name"; you're accessing state to drive your application's behavior:

try {
    $paymentProcessor->charge($amount);
} catch (PaymentFailedException $e) {
    if ($e->shouldRetry()) {
        // Log it and trigger an automatic retry after 5 minutes
        $this->queueRetry($orderId);
    } else {
        // Tell the user exactly why they need to change their card
        $this->notifyUser($e->getGatewayErrorCode());
    }
}

I've found that this approach separates the detection of the error (the service throwing the exception) from the strategy for handling it (the controller or command catching it). The service knows why it failed, but it shouldn't decide how the app recovers. By attaching that data to the exception, you pass the "why" up the chain without polluting your business logic with `if/else` blocks inside your API clients.

One last tip: don't be afraid to create an exception hierarchy. You can have a base PaymentException and then have InsufficientFundsException and ExpiredCardException extend that. This allows you to catch all payment errors in one block, or target a specific one if you have a very specialized recovery path for it.




📋 Practical Task

Implementing a Tiered Exception System for a File Upload Manager

You are building a file upload system. Instead of using generic exceptions, you need to implement a system that allows the calling code to distinguish between a "User Error" (which should be shown to the user) and a "System Error" (which should be logged and trigger an admin alert).

Requirements:

  • Create a base exception class UploadException.
  • Create two child classes: InvalidFileException (for user errors like wrong file type) and StorageLimitException (for system errors like disk full).
  • The InvalidFileException must include a method getAllowedTypes() that returns an array of strings.
  • The StorageLimitException must include a method getAvailableSpace() that returns the remaining bytes.
  • Write a try/catch block that handles InvalidFileException by printing the allowed types, and handles StorageLimitException by logging a "Critical System Error" message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.