stave.dev

Error Handling

Throw an HTTPError from anywhere in a request. The framework catches it and renders the error inside your module's frame, or as JSON for a JSON client.

The HTTPError Exception

HTTPError is an exception in core/exception/HTTPError.php, namespace Zero\Core\Exception. Throw it from a controller method, a model, a lib/ class or an attribute, and the framework handles the rest.

use Zero\Core\Exception\HTTPError;

// Basic usage - just the HTTP status code
throw new HTTPError(404);

// With a detail message
throw new HTTPError(400, "Missing required parameter: name");

// In a real endpoint
public function show($id) {
    $item = $this->model->find($id);
    if (!$item) {
        throw new HTTPError(404, "No item with ID: $id");
    }
    $this->data = ['item' => $item];
    $this->respond($this->viewPath . 'show.php');
}

The constructor takes two arguments:

Parameter Type Description
$code int HTTP status code (400, 403, 404, 500, etc.). The exception's message is the reason phrase for it, such as Not Found.
$detail ?string Optional. What went wrong, in your words. Kept in $e->detail.

How It Works

The HTTPError exception bubbles up to Application::run()'s try/catch block, which calls renderError() on the already-instantiated module:

$moduleInstance = new $Module();
try {
    self::checkAttributes($Module, $endpoint);
    $moduleInstance->{$endpoint}(...$args);
} catch (HTTPError $e) {
    $moduleInstance->renderError($e);
} catch (\ArgumentCountError $e) {
    $moduleInstance->renderError(new HTTPError(400));
}
throw new HTTPError(404)
→
Caught in Application::run()
→
$module->renderError($e)
→
Error page in module's frame

Response::renderError() sends the status line, answers the client, writes a log line and exits. Because it runs on the module that was already built, the module's frame and view paths are the ones in use: the error page has the same header and navigation as the module's other pages.

What the Client Gets

Request Response
HTML The module's view/error{code}.php in the frame when it has one. Otherwise a generic page: the code, the reason phrase and, when there is one, the detail as escaped text.
JSON HTTPError::toArray(). Whatever the endpoint had put in $this->data before it threw is dropped.
{
    "status": "error",
    "message": "Not Found",
    "detail": "Item not found",
    "code": 404
}

message is the reason phrase and detail the string the error was thrown with. detail is left out when there is none.

The Detail Reaches the Visitor

The generic page and the JSON body both show the detail to whoever made the request; no DEVMODE check hides it. Write details a visitor may read: name the missing field, not the query that failed.

Logging

Every rendered error is logged through Console as {code} - {message} : {detail}: at error for a 5xx, at warn for anything else.

Custom Error Views

Create a view named error{code}.php in the module's view/ directory:

modules/MyModule/ view/ index.php error404.php error500.php

When renderError() is called, it checks for a matching custom view file:

// Use a custom error view if one exists in the already-resolved viewPath
$view = file_exists($v = $this->viewPath . "error" . $code . ".php")
    ? $v
    : "<h1>$code - $message</h1><hr>" . ($detail ? "<h4>" . nl2br(htmlspecialchars($detail)) . "</h4><br>" : "");

$this->build($view);

Example Custom 404 Page

<div class="error-page">
    <h1>Page Not Found</h1>
    <p>The page you're looking for doesn't exist or has been moved.</p>
    <p><?= htmlspecialchars($this->title ?? '') ?></p>
    <a href="/">Return Home</a>
</div>

A custom view does not receive the detail. What it has is $this->title, which renderError() sets to Error: {message}. core/modules/Module/view/error404.php is a working example.

Which folder is searched

The error was thrown error{code}.php is looked for in
In a module That module's view/
In a submodule The top-level module's view/: it is the instance run() holds
For a URL no module answers app/frontend/view/, the view path of a plain Response. A site-wide 404 page is app/frontend/view/error404.php.

ArgumentCountError Handling

When a URL doesn't provide enough arguments for a method's required parameters, PHP throws an ArgumentCountError. The framework catches it and renders an HTTPError(400):

// Method requires $id
public function show($id) { ... }

// URL: /my-module/show (no $id provided)
// PHP throws ArgumentCountError
// Framework catches it → HTTPError(400) → "Bad Request"

So you don't check whether required arguments were provided: declare them as required parameters. Module::__call() does the same for a submodule's endpoint.

What Is Not Caught

run() catches HTTPError and ArgumentCountError and nothing else. Any other exception or PHP error is not rendered by the framework. PHP handles it as it handles any uncaught exception: no frame, no error view.

Don't Use Generic Exceptions for HTTP Errors

Throwing new \Exception('Not found') does not produce a 404 page. Catch what your own code can throw and turn it into an HTTPError with the status the client should see.

public function process() {
    try {
        $result = $this->gateway->charge($_POST['amount']);
    } catch (\RuntimeException $e) {
        throw new HTTPError(502, 'The payment service did not answer');
    }
}

The old Error class

Older sites wrote new \Zero\Core\Error(404). That class is now core/deprecated/Error.php: nothing loads it and the autoloader does not find it. Replace each call with a throw, and each use Zero\Core\HTTPError; with use Zero\Core\Exception\HTTPError;. Upgrading lists the other changes.

// Before
new \Zero\Core\Error(404, 'Map not found');

// Now
throw new \Zero\Core\Exception\HTTPError(404, 'Map not found');

Common Patterns

// 404 - Resource not found
public function show($id) {
    $item = $this->model->find($id);
    if (!$item) {
        throw new HTTPError(404, "Item not found: $id");
    }
}

// 400 - Bad input
public function update($id) {
    $name = $_POST['name'] ?? null;
    if (empty($name)) {
        throw new HTTPError(400, "Missing required field: name");
    }
}

// 403 - Custom permission check
public function admin() {
    if (!$this->user->isOwner()) {
        throw new HTTPError(403, "Owner access required");
    }
}

// 405 - Wrong HTTP method (prefer #[AllowedMethods] attribute)
public function delete($id) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new HTTPError(405, "POST required");
    }
}

// 500 - Something went wrong
public function process() {
    $result = $this->externalApi->call();
    if ($result === false) {
        throw new HTTPError(500, "External API unreachable");
    }
}
Prefer Attributes for Repetitive Checks

For authentication, HTTP method restrictions, and parameter validation, use PHP attributes like #[RequireLogin] and #[AllowedMethods('POST')] instead of manual checks. They throw HTTPError themselves, inside the same try, so a rejected request is rendered the same way. Reserve your own throws for business logic and cases where attributes don't apply.

Supported Status Codes

HTTPError::$messages maps codes from 400 to 599 to their reason phrases, including non-standard ones such as 418 (I'm a teapot) and 429 (Too Many Requests). A code that is not in the map gets the message Unspecified.

error_codes.ini

core/skeleton/config/error_codes.ini defines two constants, ERROR_CODE_403=403 and ERROR_CODE_404=404. A site changes them by having its own app/config/error_codes.ini; the file's comment gives the intent, answering a 403 as a 404 so a visitor cannot tell a forbidden page from a missing one. Nothing in core reads them: renderError() answers with the code the error was thrown with. They are there for your own throws.