Skip to content

CkException

The base of every exception CommonKit throws.

CommonKit throws only when you ask it to — with throwIfInvalid: true. By default every method answers its rejection value instead, and no exception exists. The OrNull readers go further still: they take no throwIfInvalid at all and never throw — null is their answer for any error. When you do ask, each class raises its own type — CkTextException, CkNumberException, and so on — and every one of them extends this abstract base, which itself extends PHP's RuntimeException. That gives you a choice: catch the specific type to handle one kind of failure, catch CkException to handle them all alike, or let a catch (\Throwable) you already have take it like any other error.

The constructor is protected: only a derived type creates one, with the message it has composed from its own facts.

Properties

Property Type What it holds
Input mixed The value that could not be handled, exactly as it was passed in.
Reason string Why it could not, in a few words — 'not a number', 'outside 0 to 255'.

Both are public and read-only: $error->Input, $error->Reason. The derived types add their own facts on top: most carry Expected (what the value was meant to be), CkNumberException carries TargetType, and CkDictionaryException and CkRequestException carry the Key that failed. Each type's page lists its extras.

The message is one safe log line

Every message is composed the same way — the method, the value with its type, and the reason:

CkCountry.Alpha2: cannot use "Alasca" (String) as a country — not a recognised country or code.

Two things are done on purpose:

  • Control characters become spaces. A hostile value full of line breaks or terminal escapes cannot write its own log lines or color your console — the message stays one honest line. The Input property keeps the raw value untouched.
  • Long values are cut. Text is quoted and truncated to a readable length, so a ten-megabyte payload does not become a ten-megabyte log entry.

Quick look

use SafeCoder\CommonKit\CkNumber;
use SafeCoder\CommonKit\Exceptions\CkException;

try {
    CkNumber::Integer(
        input: 'banana',
        throwIfInvalid: true
    );
} catch (CkException $error) {          // catches every CommonKit exception
    echo $error->Reason;                // -> 'not a number'   (a few plain words)
    echo $error->Input;                 // -> 'banana'         (the exact value that failed)
}

The types

One per class: CkBoolException, CkCountryException, CkDateException, CkDictionaryException, CkEmailException, CkFileException, CkGeoException, CkIntlException, CkIPException, CkMoneyException, CkNumberException, CkPayloadException, CkRequestException, CkTextException, CkUSException, CkUuidException, CkWebException.