PHP Luminova: HTTP Error Controller Handling
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 requests
onTriggerrenders the5xxtemplate for status500and the4xxtemplate for every other status. The template receivesstatusanduri(the request URI segments as an array). Luminova ships a default fallback page that is used when no custom4xxtemplate 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 keyscode,view,messageandtimestamp.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:
| Status | Reason |
|---|---|
404 | No route matched the request URI. |
405 | Routes exist, but none for the request method. |
500 | No routes are registered for the current context. |
The router then resolves the error in this order:
- Registered error handlers whose URI pattern matches the request.
- The global (
/) error handler, if registered. AppError::onTrigger().- The default error output (JSON for API requests, HTML otherwise). An
OPTIONSrequest without a handler receives an empty204response.
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.injectionis turned off. Parameters are resolved by type. Anintparameter receives the status code, and any values captured by the registered URI pattern follow it.- Handlers must return an
intstatus code, eitherSTATUS_SUCCESSorSTATUS_SILENCE.AppError::onTrigger()is called directly by the router without dependency injection, so it must keep the signature defined byErrorControllerInterface.
Implementations
You can define custom error handlers in two ways:
- Add new methods directly inside your existing
App\Errors\Controllers\AppErrorclass. - Create a separate class that implements
Luminova\Interface\RoutableInterfaceandLuminova\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 $statusfor the status code,Segmentsfor the request URI segments,and any injectable class such asApplication.
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 = '/'
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | Closure|array<int,class-string|object|string> | A closure or callable array such as [AppError::class, 'onTrigger']. |
$pattern | string | URI 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, theonSomeErrormethod inCustomFooErrorshandles errorslike404 Not Foundunder the/fooprefix (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
- Base namespace:
\App\Errors\Controllers\* - This class implements:Luminova\Interface\RoutableInterface, Luminova\Interface\ErrorControllerInterface
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
): intParameters:
| Parameter | Type | Description |
|---|---|---|
$status | int | HTTP status code associated with the error. |
$segments | Segments | The 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,messageandtimestamp. - Web requests render the
5xxtemplate for status500, and the4xxtemplate for any other status, passingstatusanduri.
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
APIcontext 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 withRouter::isApiPrefix().
Every handler can receive a Luminova\Routing\Segmentsobject by declaring it as a parameter.These are the methods you will use most often: