Luminova Framework

PHP Luminova: Exception Error Handling

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

Exception handling and logging in Luminova, including built-in exception classes, error codes, custom exceptions, and environment-specific behavior.

Luminova provides a structured exception handling system to maintain application stability and manage unexpected errors gracefully.

It includes a collection of Exception Classes, custom helper methods, and the Framework Error Handler to help you detect, log, and handle errors while providing meaningful feedback without exposing sensitive application details.

For a complete list of built-in exception codes, see the Exception and Error Codes documentation.


Examples

Extending the Base Exception Class

Extending Luminova\Exceptions\LuminovaException allows your custom exception classes to inherit the framework's built-in exception handling features while maintaining consistent behavior across your application.

// /app/Exceptions/CustomException.php

namespace App\Exceptions;

use Throwable;
use Luminova\Exceptions\LuminovaException;

/**
 * Custom exception class extending LuminovaException.
 */
class CustomException extends LuminovaException
{
    public function __construct(
        string $message,
        string|int $code = 0,
        ?Throwable $previous = null
    ) {
        parent::__construct($message, $code, $previous);
    }
}

Extending LuminovaException allows your custom exception class to accept both string and int error codes.


Custom Exception Without LuminovaException

You can create custom exception classes without extending Luminova\Exceptions\LuminovaException. However, you must implement Luminova\Interface\ExceptionInterface to ensure compatibility with Luminova's error handling system.

// /app/Exceptions/CustomException.php

namespace App\Exceptions;

use Exception;
use Throwable;
use Luminova\Interface\ExceptionInterface;

/**
 * Custom exception implementing Luminova's ExceptionInterface.
 */
class CustomException extends Exception implements ExceptionInterface
{
    public function __construct(
        string $message,
        int $code = 0,
        ?Throwable $previous = null
    ) {
        parent::__construct($message, $code, $previous);
    }

    // Add custom methods or properties as needed.
}

Note:

Unlike LuminovaException, PHP's built-in Exception only accepts integer error codes.If your custom exception needs to support both string and integer codes,you must implement that behavior yourself.


Throwing Exceptions

Luminova supports the traditional PHP throw statement and provides the throwException() helper method for handling exceptions based on the application environment.

The Usual Way

Use PHP's throw statement to throw an exception when an unexpected condition occurs.

use Luminova\Exceptions\RuntimeException;

throw new RuntimeException('Invalid configuration file.');

Environment-Aware Handling

Luminova provides the handleException() method to handle exceptions differently depending on the application environment. In production, non-fatal errors are logged without interrupting execution, while fatal errors display a generic error message to avoid exposing sensitive application details.

use Luminova\Exceptions\RuntimeException;

RuntimeException::handleException(
    'Invalid configuration file.'
);

Environment-Aware Exception Throwing

Luminova provides the throwException() method to throw exceptions.

use Luminova\Exceptions\RuntimeException;

RuntimeException::throwException(
    'Invalid configuration file.'
);

Note:throwException() handles the exception internally and does not require PHP's throw statement.


Throwing Exceptions When Input Is Missing

Use an appropriate exception class to validate required input and report invalid arguments.

use Luminova\Exceptions\InvalidArgumentException;

function loginAccount(string $username, string $password)
{
    if (!$username || !$password) {
        throw new InvalidArgumentException(
            'Username and password are required.'
        );
    }
}

Throwing as Another Exception Type

You can rethrow an existing error or exception as a different exception type. This is useful for converting errors into consistent exception types for centralized handling.

use Luminova\Exceptions\RuntimeException;
use Luminova\Exceptions\LuminovaException;

// Convert a generic Error into a RuntimeException.
LuminovaException::throwAs(
    new Error('An error occurred'),
    RuntimeException::class
);

// Rethrow directly using the target exception class.
RuntimeException::throwAs(
    new Error('An error occurred')
);

Catching Exceptions

Use PHP's try, catch, and finally blocks to intercept exceptions and handle errors without allowing them to go unhandled. This allows you to provide meaningful feedback to users while logging detailed error information for debugging.

Handling Exceptions by Code

You can catch exceptions thrown by functions such as loginAccount() and handle them based on their error codes.

use Throwable;
use Luminova\Exceptions\ErrorCode;

try {
    $user = loginAccount($username, $password);
} catch (Throwable $e) {
    // Handle errors based on their codes.

    if ($e->isCode(ErrorCode::INVALID_ARGUMENTS)) {
        echo 'Username and password are required.';
    } elseif ($e->isCode(ErrorCode::VALUE_FORBIDDEN)) {
        echo 'Access to the requested value is forbidden.';
    } else {
        echo 'Error: ' . $e->getMessage();
    }
}

Handling Exception by Type

You can catch a specific exception type, such as ErrorException, for more granular error handling.

try {
    $user = loginAccount($username, $password);
} catch (Luminova\Exceptions\ErrorException $e) {
    // Handle specific errors here.
    echo $e->getMessage();
} catch (Luminova\Exceptions\RuntimeException $e) {
    // Handle specific errors here.
    echo $e->getMessage();
} catch (\Throwable $e) {
    // Handle specific errors here.
    echo $e->getMessage();
}

Catching and Logging Exceptions

If you only need to log an exception without handling it directly, you can use the exception's log() method for Luminova exceptions and a logger for standard PHP exceptions.

use Luminova\Logger\Logger;
use Luminova\Exceptions\LuminovaException;

try {
    $pdo = loginAccount($username, $password);
} catch (\Throwable $e) {
    if ($e instanceof Luminova\Exceptions\LuminovaException) {
        // Log Luminova exception details.
        $e->log('debug');
        return;
    }

    // Log standard PHP exception details.
    Logger::exception($e);
    // Logger::debug($e->getMessage());
}

Catching and Handling Exceptions

You can handle exceptions differently depending on the application environment. For example, log errors in production while allowing exceptions to propagate during development for easier debugging.

use Luminova\Exceptions\LuminovaException;

try {
    $pdo = loginAccount($username, $password);
} catch (\Throwable $e) {
    if ($e instanceof LuminovaException) {
        // Handle Luminova exceptions.
        $e->handle();
        return;
    }

    if (PRODUCTION) {
        // Log standard PHP exceptions in production.
        Logger::error($e->getMessage());
        return;
    }

    // Rethrow exceptions during development.
    throw $e;
}

Class Definition


Methods

constructor

Create a new exception instance.

When an exception object is created with a message, an optional code, and a previous exception, it can be thrown using the throw keyword or pass the object to methods or return types.

public function __construct(string $message, string|int $code = 0, ?Throwable $previous = null)

Parameters:

ParameterTypeDescription
$messagestringThe error message for the exception.
$codestring|intThe exception code as a string or integer (default: 0).
$previous?ThrowableThe previous exception object, if available (default: null).

Usages Example

Initialize and throws an exception:

use Luminova\Exceptions\LuminovaException;
use Luminova\Exceptions\RuntimeException;

try{
    throw new RuntimeException('An error occurred');
}catch(LuminovaException $e){
    // handle exception
}

isCode

Checks if the current exception's code matches a given code or any in an array.

Compares the provided code(s) against the exception's string code (if available) or its numeric code as a fallback.

public function isCode(string|array|int $code): bool

Parameters:

ParameterTypeDescription
$codestring&#124;array<array-key,mixed>&#124;intThe code or list of codes to compare against.

Return:

bool - Returns true if a match is found, otherwise false.


setCode

Sets the exception code.

public function setCode(string|int $code): self

Parameters:

ParameterTypeDescription
$codestring&#124;intThe string or integer representation of the exception code.

Return:

self - Returns the current instance for method chaining.


setFile

Sets the file where the error occurred.

public function setFile(string $file): self

Parameters:

ParameterTypeDescription
$filestringThe file where the error occurred.

Return:

self - Returns the current instance for method chaining.


setLine

Sets the line number where the error occurred.

public function setLine(int $line): self

Parameters:

ParameterTypeDescription
$lineintThe line number of the error.

Return:

self - Returns the current instance for method chaining.


getDescription

Get a formatted message.

This method returns a filtered exception message, ensuring messages doesn't contain any sensitive information like private server paths.

public function getDescription(): string

Return:

string - Return the filtered exception message.

Example:

You can retrieve a filtered error message that omits file details:

use Luminova\Exceptions\ErrorException;

try {
    $pdo = loginAccount($username, $password);
} catch (ErrorException $e) {
    echo $e->getDescription(); // Get a user-friendly error message.
}

getName

Get an exception error name.

This method returns a humanized exception name based on the exception code.

public function getName(): string

Return:

string - Return the name of the thrown exception.

Example:

To retrieve a user-friendly name for the exception, use the following method:

use Luminova\Exceptions\ErrorException;

try {
   $pdo = loginAccount($username, $password);
} catch (ErrorException $e) {
   echo $e->getName(); // Get a human-readable name for the error.
}

getErrorCode

Get a string or an integer error code for thrown exception.

Unlike getCode method, this method returns an integer or string error code of the exception. It first checks if a string error code is set ($strCode), if not, falls back to the numeric error code.

public function getErrorCode(): string|int

Return:

string|int - Return the error code as either a string or an integer. Returns the string error code if set, otherwise returns the numeric error code.


getBacktrace

Retrieve the las debug tracer.

This attempt to get last debug backtrace from the exception or shared error context.

public function getBacktrace(): array

Return:

array<array-key,mixed> - Return the debug backtrace, or an empty array if not available.

This method checks for the exception backtrace, if not available it checks for the stored debug backtrace in the runtime memory Runtime::lastErrorBacktrace() if still unavailable, it returns an empty array.

Example:

You can obtain backtrace information from an exception:

use Luminova\Exceptions\ErrorException;

try {
   $pdo = loginAccount($username, $password);
} catch (ErrorException $e) {
   print_r($e->getBacktrace()); // Print backtrace for debugging.
}

toString

Returns a formatted error message with code, file, and line details.

public function toString(): string

Return:

string - Return the formatted error message with code, file, and line number.

Example:

use Luminova\Exceptions\RuntimeException;

try{
   throw new RuntimeException('An error occurred');
}catch(RuntimeException $e){
   echo $e->toString();
   // Output: RuntimeException: An error occurred in /path/to/file.php:12 (code: 123)
}

Note:The toString and built-in Exception __toString returns different format.The returned format for toString is: Class: message in path/to/file.php:line (code: N).


toArray

Converts the exception into a standardized array representation.

Includes the exception code, descriptive title, class name, message,source location, previous exception details, and stack trace.

public function toArray(bool $sanitize = false): array

Parameters:

ParameterTypeDescription
$sanitizeboolSanitize messages and shorten file paths, including for previous exceptions (default false).

Return:

array<string,mixed> - Returns the formatted exception details.

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.

Example:

use Luminova\Exceptions\RuntimeException;

try{
   throw new RuntimeException('An error occurred');
}catch(RuntimeException $e){
    print_r($e->toArray());
    //    Array(
    //         code: string|int,
    //         title: string,
    //         class: class-string,
    //         message: string,
    //         file: string,
    //         line: int,
    //         previous: array,
    //         trace: array
    //     )
}

log

Logs the exception message to the configured logger.

Uses App\Config\Logger. If asynchronous logging is enabled, logs use Fiber for async processing. In production, if logger.mail.logs or logger.remote.logs is set, logs are sent via email or to a remote server.

Log Levels:

  • emergency - Log emergency error that need attention.
  • alert - Log alert message.
  • error - Log minor error.
  • warning - Log a warning message.

For more log level see Log Levels documentation.

public function log(?string $dispatch = null): void

Parameters:

ParameterTypeDescription
$dispatch?stringA log level, email address, or remote URL to send the error to (default: null).

Example:

This example demonstrates catching an exception and logging an exception message with a custom log level.

use Luminova\Exceptions\RuntimeException;

try{
    throw new RuntimeException('An error occurred');
}catch(RuntimeException $e){
    $e->log('debug');
}

handle

Handles exceptions safely depending on the application environment and error type.

This method ensures that exceptions are processed appropriately:

  • In CLI mode: either re-throws the exception (if enabled) or shows a CLI-friendly error detail.
  • In production: logs the error, shows a user-friendly page for fatal errors, and prevents leaks of sensitive information.
  • In development: re-throws the exception so it can be displayed directly.

The handler also prevents recursive exception handling and ensures consistent shutdown behavior.

public function handle(): void

Throws:

  • Luminova\Exceptions\LuminovaException<\T, Throwable> - Re-throws the exception in non-production environments or when explicitly configured for CLI.

Example:

This below example shows how you can catch an exception and handle it with handle method.

use Luminova\Exceptions\RuntimeException;

try{
    throw new RuntimeException('An error occurred');
}catch(RuntimeException $e){
    $e->handle();
}

throwException

Creates and handles an exception gracefully.

public static function throwException(
    string $message,
    string|int $code = 0,
    ?Throwable $previous = null
): void

Parameters:

ParameterTypeDescription
$messagestringThe exception message.
$codestring&#124;intThe exception code (default: 0).
$previous?ThrowableThe previous exception, if available (default: null).

Throws:

  • T<Luminova\Exceptions\LuminovaException> - Throws in development environment or if the exception code is fatal, otherwise log the information.

Example:

The following example demonstrates how to handle an exception gracefully in a production environment.For more error codes, refer to Exceptions and Error Handling.

use Luminova\Exceptions\ErrorCode;
use Luminova\Exceptions\LuminovaException;
use Luminova\Exceptions\RuntimeException;

try {
    throw new RuntimeException('An error occurred');
} catch (\Throwable $e) {
    if($e instanceof LuminovaException) {
        $e->handle();
        return;
    }

    // If not instance of LuminovaException, create safe exception handler from the exception object.
    RuntimeException::throwException(
        $e->getMessage(),
        ErrorCode::COMPILE_ERROR,
        $e
    );
}

handleException

Create an exception using the called class and dispatch it through the framework’s exception handler. If a previous throwable is provided, its location is used.

public static function handleException(
    string $message,
    string|int $code = 0,
    ?Throwable $previous = null
): void

Parameters:

ParameterTypeDescription
$messagestringException message.
$codestring&#124;intException code (default 0).
$previous?ThrowablePrevious exception to preserve (default null).

throwAs

Rethrow or handle an exception as a specified exception class.

If the given Throwable is already an instance of Luminova\Exceptions\LuminovaException, it will be handled directly. Otherwise, a new exception of the specified class (or the current class if not provided) will be created with the same message, code, and previous exception, then handled.

public static function throwAs(Throwable $e, ?string $abstract = null): void

Parameters:

ParameterTypeDescription
$eThrowableThe original exception object to be thrown or handled.
$abstract?stringThe new exception class to throw as (e.g., Luminova\Exceptions\RuntimeException). Defaults to the current class if null.

Throws:

  • \T<Throwable> - Throws the exception from the called class.

Example:

Throw Error exception as RuntimeException and handle it gracefully:

use Luminova\Exceptions\LuminovaException;
use Luminova\Exceptions\RuntimeException;

try {
    throw new \Error('An error occurred');
} catch (\Throwable $e) {
    if($e instanceof RuntimeException) {
        $e->handle();
        return;
    }

    LuminovaException::throwAs($e, RuntimeException::class);
}