PHP Luminova: Error Handling & Reporting
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\RuntimeExceptionbefore 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 callsshouldHandleErrorShutdown()instead. ReturningfalsefromshouldHandleErrorShutdown()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=dbMessage 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. Thecolorattribute 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) importantMethods
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
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | Deprecation message (supports sprintf placeholders). |
$since | ?string | Version 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). |
$mode | int | How the deprecation is reported (default: 0). |
Return:
bool - Returns true if the message was logged or the PHP error was triggered.
Modes:
| Mode | Behavior |
|---|---|
0 | Logs the message at notice level. Safe for production. |
1 | Terminates the application with HTTP status 502 and the message. |
2 | Throws an ErrorException with code ErrorCode::DEPRECATED, pointing to the caller's file and line. |
| any other value | Triggers a PHP E_USER_DEPRECATED error. |
Throws:
- Luminova\Exceptions\ErrorException - When
$modeis2.
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
): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The message containing <link> or <highlight> placeholders. |
$newTab | bool | Whether 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()orhsla()values. Any other value falls back toyellow. - 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): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$e | ?Throwable | The exception or error to convert. |
$sanitize | bool | When 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.
| Key | Type | Description |
|---|---|---|
code | string|int | Original Luminova error code or native throwable code. |
title | string | Name resolved from the numeric exception code. |
class | string | Fully qualified throwable class. |
message | string | Exception message. |
file | string | Source file or display path. |
line | int | Source line number. |
trace | array<int,array<string,mixed>> | Stack frames. |
previous | array<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 = []
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$level | string | The log level (e.g, error, notice). |
$message | string | The message to log. |
$context | array<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): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$error | Throwable | The error or exception to display. |
$status | int | HTTP status code for the response (default: 500). |
Return:
never - Terminates after displaying or handling the error.
Behavior:
| Context | Output |
|---|---|
| CLI | Prints the exception to the terminal and exits with code 1. |
| Web request | Calls 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 request | Sends 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 = [],
): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$fullPath | string | Absolute path to the error template file. |
$error | Throwable | The exception or error being handled. |
$status | int | HTTP response status code (default: 500). |
$description | ?string | Optional description passed to the template as is. Templates should fall back to their own default when it is null. |
$options | array<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:12or/path/file.php on line 12 - Everything from
thrown inonward
public static function sanitize(string $message): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The 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): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The 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
): neverParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | Error message. |
$code | string\|int | Framework error code. |
$file | string\|null | Optional source file. |
$line | int\|null | Optional line number. |
Return:
never - Always throws.
Throws:
Luminova\Exceptions\ErrorException- The error exception created from the supplied details.