Luminova Framework

PHP Luminova: Error Handling & Reporting

Last updated: 2026-11-28 20:57:12

Luminova’s centralized error handling system. It automatically catches every error in your application and routes it to Luminova’s final controller for logging or presents a friendly UI.

The Error class is Luminova's built-in error handling system. It catches PHP errors, uncaught exceptions and fatal shutdown errors, then either logs them or displays them with helpful details, depending on the environment.

All methods are static, so you can call them anywhere in your project without creating an object.

The handlers are registered for you by Luminova\Boot. Boot::http(), Boot::init() and Boot::cli() all register them. Boot::autoload() does not, because it only loads the framework modules. In most cases you don't need to set anything up manually.

Note:Uncaught exceptions that are not Luminova exceptions are wrapped in a Luminova\Exceptions\RuntimeException before they are handled. The original file and line are preserved, so the error page still points to where the problem started.

Note:On shutdown, the handler calls the onShutdown() hook of your application class. When the shutdown is caused by an error, it calls shouldHandleErrorShutdown() instead. Returning false from shouldHandleErrorShutdown() stops Luminova's default error handling, so your application takes over.


When Do You Need to Call Error Yourself?

The registration, PHP error, uncaught exception and shutdown handlers are internal. You never call them directly.

The public methods below are the ones worth using in application code. Use them to report deprecations, convert exceptions to arrays, clean or mask messages, format messages, write to the log, or render a custom error page.


Class Definition

  • Class namespace: Luminova\Foundation\Error\Error
  • This class is marked as final and can't be subclassed

Examples

Throw an Error with the Caller Location

Construct an ErrorException with a message and code. Pass the filename and line to specify the reported location.

use Luminova\Exceptions\ErrorCode;
use Luminova\Exceptions\ErrorException;

throw new ErrorException(
    'Invalid configuration value.',
    ErrorCode::INVALID,
    filename: __FILE__,
    line: __LINE__
);

Report a Deprecation

use Luminova\Foundation\Error\Error;

Error::deprecate(
    'Method %s() is deprecated. Use %s() instead.',
    '1.5.0',
    ['foo', 'getFoo']
);

Convert an Exception to an Array

use Throwable;
use Luminova\Foundation\Error\Error;

try {
    // Your code...
} catch (Throwable $e) {
    $error = Error::toArray($e, sanitize: true);

    // $error['code'], $error['title'], $error['message'], $error['file'], ...
}

Mask Sensitive Values

Error::mask keeps the key and separator and replaces the value with asterisks.

use Luminova\Foundation\Error\Error;

echo Error::mask('Connection failed: password=secret123, host=db');

// Connection failed: password=********, host=db

Message Prettifier

Error::prettify converts the special placeholders <link> and <highlight> in a message into styled output that adapts to both web and CLI environments.

In web contexts:

  • <link>URL</link> is rendered as a clickable link:

    <a class="error-link" href="URL" target="_blank" rel="noopener">URL</a>
  • <highlight color="red">Text</highlight> is rendered as a span:

    <span class="error-highlight" style="color:red">Text</span>

In CLI contexts:

  • <link>URL</link> is printed as plain text when the terminal doesn't support ANSI. When ANSI is supported but colors are not, it is printed as a clickable terminal hyperlink. When colors are supported, it is printed underlined.
  • <highlight>Text</highlight> is printed in yellow when colors are supported, or as plain text otherwise. The color attribute is ignored.

Only valid http(s) URLs and mailto: addresses are converted inside <link>. If the value is not valid, the whole tag is returned as escaped text.

use Luminova\Foundation\Error\Error;

echo Error::prettify(
    'See <link>https://luminova.ng/</link> and <highlight color="red">important</highlight>'
);

Output in a browser:

See <a class="error-link" href="https://luminova.ng/" target="_blank" rel="noopener">https://luminova.ng/</a>
and <span class="error-highlight" style="color:red">important</span>

Output in CLI:

See https://luminova.ng/ and (highlighted) important

Methods

deprecate

Reports a deprecation using logging, termination, an exception, or a PHP warning, depending on $mode.

If $since is not empty, (since {version}) is appended to the message. If $arguments is provided, the message is formatted with vsprintf.

public static function deprecate(
    string $message,
    ?string $since = null,
    ?array $arguments = null,
    int $mode = 0
): bool

Parameters:

ParameterTypeDescription
$messagestringDeprecation message (supports sprintf placeholders).
$since?stringVersion when the deprecation started (e.g., 1.5.0) (default null).
$arguments?array<array-key,mixed>Optional values to replace placeholders in the message (default null).
$modeintHow the deprecation is reported (default: 0).

Return:

bool - Returns true if the message was logged or the PHP error was triggered.

Modes:

ModeBehavior
0Logs the message at notice level. Safe for production.
1Terminates the application with HTTP status 502 and the message.
2Throws an ErrorException with code ErrorCode::DEPRECATED, pointing to the caller's file and line.
any other valueTriggers a PHP E_USER_DEPRECATED error.

Throws:


prettify

Converts <link> and <highlight> placeholders into styled output for the web or CLI. See Message Prettifier for the full output formats.

public static function prettify(
    string $message,
    bool $newTab = true
): string

Parameters:

ParameterTypeDescription
$messagestringThe message containing <link> or <highlight> placeholders.
$newTabboolWhether web links open in a new tab (default: true). Ignored in CLI.

Return:

string - The message with placeholders replaced. An empty message returns an empty string.

Notes:

  • Highlight colors on the web accept CSS color names, hex values, and rgb(), rgba(), hsl() or hsla() values. Any other value falls back to yellow.
  • Only the content of matched placeholders is escaped. Text outside the placeholders is returned unchanged, so escape untrusted text before passing it in.

toArray

Converts an exception or error into a standard array.

Luminova exceptions use getErrorCode() for code, which can be a string, and getBacktrace() for trace. Other throwables use getCode() and getTrace(). In both cases title is the name mapped from the numeric getCode() value.

public static function toArray(?Throwable $e, bool $sanitize = false): array

Parameters:

ParameterTypeDescription
$e?ThrowableThe exception or error to convert.
$sanitizeboolWhen true, the message is cleaned with sanitize and the file path is converted to a display path. Applies to previous exceptions too (default: false).

Return:

array<string,mixed> - Returns the formatted exception details, or an empty array if no exception is provided.

KeyTypeDescription
codestring&#124;intOriginal Luminova error code or native throwable code.
titlestringName resolved from the numeric exception code.
classstringFully qualified throwable class.
messagestringException message.
filestringSource file or display path.
lineintSource line number.
tracearray<int,array<string,mixed>>Stack frames.
previousarray<string,mixed>Previous exception details, or an empty array.

tryLog

Attempts to log a message with the framework logger, falling back to a log file and then to PHP's default error log.

The framework logger is used once the application boot warmup has completed. If it can't dispatch the message, or boot has not completed, the message is written to /writeable/logs/{level}.log. If the log directory can't be created or the file can't be written, PHP's default error log is used.

public static function tryLog(
    string $level,
    string $message,
    array $context = []
): bool

Parameters:

ParameterTypeDescription
$levelstringThe log level (e.g, error, notice).
$messagestringThe message to log.
$contextarray<string,mixed>Optional context passed to the framework logger (default []).

Return:

bool - Returns true if the message was logged successfully.


display

Displays the appropriate system error page for an error or exception.

public static function display(Throwable $error, int $status = 500): never

Parameters:

ParameterTypeDescription
$errorThrowableThe error or exception to display.
$statusintHTTP status code for the response (default: 500).

Return:

never - Terminates after displaying or handling the error.

Behavior:

ContextOutput
CLIPrints the exception to the terminal and exits with code 1.
Web requestCalls render with the errors.php template. The template in /app/Errors/Defaults/ is used when it exists, otherwise the framework template. The bundled template shows full details outside production, and a generic message with no details in production.
API requestSends a JSON response with no-cache headers and a Retry-After of 60 seconds. In production the message and file path are sanitized, and trace and previous are removed. In other environments the raw values are returned, and trace and previous are included only when SHOW_DEBUG_BACKTRACE is enabled.

The PHP display_errors and display_startup_errors settings are turned off while the response is built and restored afterwards. When SHOW_DEBUG_BACKTRACE is enabled, the current backtrace is recorded before output.


render

Renders an error response using a template file.

PHP error display is turned off, all output buffers are cleared, and no-cache headers are sent with a Retry-After of 60 seconds. The template is then included with the supplied $options extracted into its scope.

If the template file does not exist, the application terminates with an HTML response. The response body is $description (or an empty string), followed by a line break and the error message. In production the message is sanitized.

public static function render(
    string $fullPath,
    Throwable $error,
    int $status = 500,
    ?string $description = null,
    array $options = [],
): never

Parameters:

ParameterTypeDescription
$fullPathstringAbsolute path to the error template file.
$errorThrowableThe exception or error being handled.
$statusintHTTP response status code (default: 500).
$description?stringOptional description passed to the template as is. Templates should fall back to their own default when it is null.
$optionsarray<string,mixed>Extra variables made available to the template. Keys that clash with existing variables are prefixed with __ (default []).

Return:

never - Terminates after sending the error response.

Available in the template: $error, $status, $description, $title (for example 500 Internal Server Error) and the keys from $options.

Example:

use Luminova\Foundation\Error\Error;

Error::render(
    APP_ROOT . '/resources/errors/500.php',
    $error,
    500,
    'An unexpected error occurred.',
    ['requestId' => 'abc123']
);

sanitize

Removes environment details and diagnostic output from an error message so only the readable text remains.

The following are removed or masked:

  • The application root path (APP_ROOT)
  • Values of sensitive keys, using mask
  • Everything from Stack trace: onward
  • A trailing PHP file location, such as in /path/file.php:12 or /path/file.php on line 12
  • Everything from thrown in onward
public static function sanitize(string $message): string

Parameters:

ParameterTypeDescription
$messagestringThe raw error or exception message.

Return:

string - Returns the cleaned and trimmed message.


mask

Masks sensitive values in a message, such as passwords, tokens and secrets.

The key and its separator (= or :) are kept, and the value is replaced with ********. Matching is case insensitive. An unquoted value ends at whitespace, a comma or a semicolon, and quoted values are masked whole.

The built-in keys are password, passwd, pass, pwd, secret, credential, credentials, authorization, auth and token. You can add more keys with App\Config\Security::$maskErrorMessageCredentials, which must be an array of strings.

public static function mask(string $message): string

Parameters:

ParameterTypeDescription
$messagestringThe message to mask.

Return:

string - Returns the message with sensitive values masked.


trigger

Throw a framework error exception with the supplied details. Missing file or line information is filled from a backtrace.

public static function trigger(
    string $message,
    string|int $code = ErrorCode::USER_NOTICE,
    ?string $file = null,
    ?int $line = null
): never

Parameters:

ParameterTypeDescription
$messagestringError message.
$codestring\|intFramework error code.
$filestring\|nullOptional source file.
$lineint\|nullOptional line number.

Return:

never - Always throws.

Throws:

  • Luminova\Exceptions\ErrorException - The error exception created from the supplied details.