DEV Community

Cover image for Built Notes 01: Error Codes and Your Own Exception System
Mekad Alibrahem for Aristonis

Posted on Originally published at aristonis.org

Built Notes 01: Error Codes and Your Own Exception System

Framework exceptions show language or database errors, not the business case, so they are hard to debug. With an error code, debugging is faster and easier when an error happens.

The problem

Two customers tried to buy the same item from the store at the same moment. The database locked the row (lock for update), so the last one got an error. Without a code, that error only says the sale failed.

Finding out why means opening the production server, searching the logs, sometimes running database queries, checking the monitors if you have them. Meanwhile customers complain in the support channel about an error nobody understands.

I built this system with error codes from day one, so I never paid that cost here.

The idea

An error code should explain itself. Give it a module prefix, like store.item_sold_out, and you know exactly which component failed. That closes the search scope.

How, in Laravel

  1. A contract: every code knows its HTTP status.
interface ErrorCode extends BackedEnum
{
    public function status(): int;
}
Enter fullscreen mode Exit fullscreen mode
  1. One enum per module. The value is <module>.<case> and never changes once shipped.
enum StoreErrorCode: string implements ErrorCode
{
    case ItemSoldOut = 'store.item_sold_out';
    case PaymentDeclined = 'store.payment_declined';

    public function status(): int
    {
        return match ($this) {
            self::ItemSoldOut => 409,
            self::PaymentDeclined => 402,
        };
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. One base exception that carries the code.
class AppException extends Exception
{
    public function __construct(
        public readonly ErrorCode $errorCode,
        public readonly array $details = [],
    ) {
        parent::__construct($errorCode->value);
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Throw the business case, not a framework error. This runs inside the transaction, after lockForUpdate() on the product row, so the second buyer waits, sees the stock, and gets a clear code.
if ($product->stock < $quantity) {
    throw new AppException(StoreErrorCode::ItemSoldOut, [
        'product_id' => $product->public_id,
        'available' => $product->stock,
    ]);
}
Enter fullscreen mode Exit fullscreen mode
  1. One responder for every failure, in bootstrap/app.php. It maps the framework's own exceptions to codes too, so validation, auth, a missing model or a lost unique race never leak stack details. Every response carries a request_id, the same id the logs carry.
public static function render(Throwable $e): JsonResponse
{
    return match (true) {
        $e instanceof AppException => self::respond($e->errorCode, $e->status(), $e->details),
        $e instanceof ValidationException => self::respond(CoreErrorCode::ValidationFailed, details: ['fields' => self::failedRules($e)]),
        $e instanceof AuthenticationException => self::respond(CoreErrorCode::Unauthenticated),
        $e instanceof ModelNotFoundException => self::respond(CoreErrorCode::NotFound),
        $e instanceof QueryException && $e->getCode() === '23505' => self::respond(CoreErrorCode::Conflict),
        default => self::respond(CoreErrorCode::InternalError),
    };
}

private static function respond(ErrorCode $code, ?int $status = null, array $details = []): JsonResponse
{
    return response()->json([
        'error' => ['code' => $code->value, 'details' => (object) $details],
        'meta' => ['request_id' => AssignRequestId::current()],
    ], $status ?? $code->status());
}
Enter fullscreen mode Exit fullscreen mode

The response:

{
  "error": { "code": "store.item_sold_out", "details": { "product_id": "01J...", "available": 0 } },
  "meta": { "request_id": "01JREQ..." }
}
Enter fullscreen mode Exit fullscreen mode

Two tests guard it: one fails when two modules share a code, and one pins every shipped code in a file, so renaming a code a client already uses breaks the build first.

Why it helps users

A clean, standard error code lets the UI and the API show users a clear message, without exposing any sensitive data.

Note: remember to hide any sensitive data in logs or messages. details carries ids and numbers, never emails, tokens or card data.

Same idea in Java

One exception per module, each carrying its code. The code also says who is at fault (client or server) and which context keys it always sends, so a client can build its own message. The exception message is for the developer log only.

public enum StoreErrorCode implements ErrorCode {
    ITEM_SOLD_OUT(ErrorKind.CLIENT, "productId", "available");

    // code() = namespace() + "." + name()  ->  "aristonis.store.ITEM_SOLD_OUT"
    @Override public String namespace() { return "aristonis.store"; }
    // kind() and contextKeys() return the constructor values
}

public final class StoreException extends BaseException {
    public StoreException(StoreErrorCode code, String message, Map<String, Object> context) {
        super(code, message, context);
    }
}

// throw new StoreException(StoreErrorCode.ITEM_SOLD_OUT, "stock 0 after lock",
//         Map.of("productId", id, "available", 0));
Enter fullscreen mode Exit fullscreen mode

Takeaway

A framework exception tells you what broke at the stack level (a null value, a wrong type). An error code tells you which business rule and use case broke.


Originally published on aristonis.org.

Top comments (0)