Luminova Framework

PHP Luminova: HTTP Error Controller Handling

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

Handles application-wide errors in Luminova HTTP controllers, allowing you to define custom error responses globally or by route prefix.

The Error Controller classes in Luminova provides a centralized way to handle errors for HTTP controllers, whether you are using attribute-based routing or method-based routing.

By implementing Luminova\Interface\ErrorControllerInterface, you define how errors are displayed for different request contexts. Its onTrigger method is the default entry point for HTTP errors and works together with the router's trigger method, which raises an error from an HTTP status code. You can add your own handler methods to this class, or create separate classes for them.


What the App Error Controller does

  • Renders error templates for web requestsonTrigger renders the 5xx template for status 500 and the 4xx template for every other status. The template receives status and uri (the request URI segments as an array). Luminova ships a default fallback page that is used when no custom 4xx template exists in your views.

  • Returns JSON for API requestsWhen the first URI segment matches the configured API prefix (see Router::isApiPrefix()), the response is JSON with the keys code, view, message and timestamp.

  • Manual error triggeringCall Router::trigger(statusCode) anywhere in your application to show a consistent error response.

This gives you complete control over how errors are displayed,so users see meaningful responses instead of generic error pages.


How errors are resolved

Errors reach the handlers in two different ways, and the order is not the same for both.

Manual trigger: Luminova\Routing\Router::trigger($status) calls AppError::onTrigger() first when that method exists, then terminates. If that method is absent, the router can fall back to registered handlers.

Router errors: When the router cannot serve a request, it raises one of these statuses on its own:

StatusReason
404No route matched the request URI.
405Routes exist, but none for the request method.
500No routes are registered for the current context.

The router then resolves the error in this order:

  1. Registered error handlers whose URI pattern matches the request.
  2. The global (/) error handler, if registered.
  3. AppError::onTrigger().
  4. The default error output (JSON for API requests, HTML otherwise). An OPTIONS request without a handler receives an empty 204 response.

A handler that returns STATUS_SUCCESS or STATUS_SILENCE is treated as handled and stops the process. Any other return value lets the router continue to the next step.


Note:

  • Error handler methods must be public and defined in an instantiable class that implements Luminova\Interface\RoutableInterface.
  • Handlers can be static only when the class also implements Luminova\Interface\ErrorControllerInterface. Otherwise, use a non-static method.
  • Dependency injection is always enabled for error handlers, even when feature.route.dependency.injection is turned off. Parameters are resolved by type. An int parameter receives the status code, and any values captured by the registered URI pattern follow it.
  • Handlers must return an int status code, either STATUS_SUCCESS or STATUS_SILENCE.
  • AppError::onTrigger() is called directly by the router without dependency injection, so it must keep the signature defined by ErrorControllerInterface.

Implementations

You can define custom error handlers in two ways:

  1. Add new methods directly inside your existing App\Errors\Controllers\AppError class.
  2. Create a separate class that implements Luminova\Interface\RoutableInterface and Luminova\Interface\ErrorControllerInterface.

Custom Class Example

Below is an example of a dedicated class for handling custom errors:

// /app/Errors/Controllers/CustomFooErrors.php

namespace App\Errors\Controllers;

use Luminova\Routing\Segments;
use Luminova\Interface\RoutableInterface;
use Luminova\Interface\ErrorControllerInterface;
use function Luminova\Funcs\view;

class CustomFooErrors implements RoutableInterface, ErrorControllerInterface
{
    public static function onTrigger(int $status, Segments $segments): int
    {
        return view('4xx')->render(
            ['status' => $status, 'uri' => $segments->all()],
            $status
        );
    }

    /**
     * Example of a custom error handling method.
     *
     * @param int $status The HTTP status code of the error.
     * @param Segments $segments The request URI segments.
     *
     * @return int Must return STATUS_SUCCESS or STATUS_SILENCE.
     */
    public static function onSomeError(
        int $status,
        Segments $segments
    ): int
    {
        return view('error')->render(
            ['status' => $status, 'uri' => $segments->all()],
            $status
        );
    }
}

Note:

A handler can declare only the parameters it needs.Use int $status for the status code, Segments for the request URI segments,and any injectable class such as Application.


Registering Handlers

You can register custom error handlers with attribute-based routing, context-based routing, or directly with Router::onError(). In every case the handler must be a callable, either a closure or a [class, method] array.

  • Closure example:fn(int $status, Segments $segments): int => AppError::onTrigger($status, $segments)
  • Callable array example:[AppError::class, 'onTrigger']

Router::onError

Registers an error handler globally, or for a specific URI pattern. If a handler is already registered for the same pattern, it is replaced. See Router::onError, documentation.

Example:

public static function onError(
    Closure|array $handler,
    string $pattern = '/'
): void

Parameters:

ParameterTypeDescription
$handlerClosure&#124;array<int,class-string&#124;object&#124;string>A closure or callable array such as [AppError::class, 'onTrigger'].
$patternstringURI pattern. Use '/' for the global handler (default '/').

Context-Based Handling

If you are not using attributes, you can register an error handler for each routing context in public/index.php. The context method accepts an array of Prefix objects, or an array of context definitions.

Example using Prefix objects:

// /public/index.php

use Luminova\Boot;
use Luminova\Routing\Prefix;
use App\Errors\Controllers\AppError;

Boot::http()->router->context([
    new Prefix(Prefix::WEB, [AppError::class, 'onTrigger']),
    new Prefix(Prefix::API, [AppError::class, 'onTrigger']),
    new Prefix(
        'dashboard', /* URI prefix where this handler applies */
        [AppError::class, 'onDashboardError'] /* Error handler */
    ),
])->run();

Example using arrays:

// /public/index.php

use Luminova\Boot;
use App\Errors\Controllers\AppError;

Boot::http()->router->context([
    'dashboard' => [
        'prefix' => 'dashboard',
        'onError' => [AppError::class, 'onDashboardError']
    ],
])->run();

Attribute-Based Handling

When using attributes, you can attach error handlers directly to your controllers (class scope).

Using the non-repeatable Prefix attribute:

The onError argument is optional. For more information see the URI Prefix Attribute documentation.

// /app/Controllers/Http/FooController.php

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController as Controller;
use Luminova\Attributes\Prefix;
use App\Errors\Controllers\AppError;

#[Prefix(
    pattern: '/foo/(:root)', /* URI pattern */
    onError: [AppError::class, 'onSomeError'] /* Error handler */
)]
class FooController extends Controller {}

Using the repeatable Error attribute:

The onError argument is required, and a RouterException is thrown if it is missing or not callable. For more information see the Error Attribute documentation.

// /app/Controllers/Http/FooController.php

namespace App\Controllers\Http;

use Luminova\Base\Http\AbstractController as Controller;
use Luminova\Attributes\Error;
use App\Errors\Controllers\CustomSomeErrors;

#[Error(
    prefix: 'web', /* All web based requests */
    pattern: '/(:root)', /* URI pattern */
    onError: [CustomSomeErrors::class, 'onTrigger'] /* Error handler */
)]
#[Error(
    prefix: 'foo', /* Requests under the foo prefix */
    pattern: '/foo/(:root)',
    onError: [CustomSomeErrors::class, 'onSomeError']
)]
class FooController extends Controller {}

These examples show how to register error handlers globally (via router contextor Router::onError()) or directly inside a controller (via attributes).For instance, the onSomeError method in CustomFooErrors handles errorslike 404 Not Found under the /foo prefix (e.g., https://example.com/foo/invalid-route).

For inline method scope error handling using the Route attribute, see the Route Attribute documentation.


Class Definition


Methods

onTrigger

Handle a manually triggered routing error.

This method is invoked when the routing system explicitly triggers an error status (e.g., via Router::trigger(404)). It is also the fallback handler for router errors that no registered handler resolved.

public static function onTrigger(
    int $status,
    Segments $segments
): int

Parameters:

ParameterTypeDescription
$statusintHTTP status code associated with the error.
$segmentsSegmentsThe request URI segments associated with the error.

Return:

int - Return response status code, either STATUS_SUCCESS or STATUS_SILENCE.

Default behavior:

  • API requests receive a JSON response with code, view, message and timestamp.
  • Web requests render the 5xx template for status 500, and the 4xx template for any other status, passing status and uri.

Example:

You can trigger an error anywhere in your application.

// app/Controllers/Http/FooController.php
// app/Modules/<?module>/Controllers/Http/FooController.php

$this->app->router::trigger(500);

// Or
Luminova\Routing\Router::trigger(500);

This is the global fallback handler for manually triggered errors.


Custom Error Handlers

AppError ships with onTrigger only. The methods below are examples of handlers you can add yourself, then register with any of the approaches above.

// /app/Errors/Controllers/SomeErrors.php
namespace App\Errors\Controllers;

use Luminova\Routing\Segments;
use Luminova\Interface\RoutableInterface;
use Luminova\Interface\ErrorControllerInterface;
use function Luminova\Funcs\{view, response};

class SomeErrors implements RoutableInterface, ErrorControllerInterface
{
    /**
     * Default handler.
     */
    public static function onTrigger(int $status, Segments $segments): int
    {
        return STATUS_SILENCE;
    }

    /**
     * Handle web based routing errors.
     */
    public static function onWebError(int $status, Segments $segments): int
    {
        return view('4xx')->render(
            ['status' => $status, 'uri' => $segments->all()],
            $status
        );
    }

    /**
     * Handle API routing errors.
     */
    public static function onApiError(int $status, Segments $segments): int
    {
        return response($status)->json([
            'code' => $status,
            'message' => "The endpoint [{$segments->toString()}] does not exist."
        ]);
    }
}

The API context is identified by checking whether the first part of the requestURL matches your API prefix (for example, https://example.com/api/...).This check is performed with Router::isApiPrefix().

Every handler can receive a Luminova\Routing\Segmentsobject by declaring it as a parameter.These are the methods you will use most often: