Exception Handling
Resilient, layered error handling from the earliest bootstrap phase to fully initialized application runtimes.
APPNETOS separates early bootstrap protection from the central Core exception handler. Structured exceptions carry internal diagnostics and safe public messages, while dedicated response handling selects standalone HTML or standardized JSON problem details. Logging and recovery remain available even when ordinary application services fail.
Exceptions represent errors and their context; the central handler performs logging, debugging, HTTP classification and response generation. Exception objects do not render, log or terminate execution themselves.
Architecture and ownership
The error-handling system has two stages, plus an independent last-resort response path. The
bootstrap
stage is intentionally independent of Core\Registry, Core\Log, Twig, the
DebugBar and application runtime services.
| Stage | Component | Responsibility |
|---|---|---|
| Pre-Core | Bootstrap\ErrorHandling\ErrorHandlingBootstrap |
PHP settings, early error log, native error/exception/fatal handlers, minimal CLI/HTTP output. |
| Core | Core\Exception\Handler\Base |
Throwable classification, structured logging, Debug integration, standalone HTML or JSON response. |
| Final fallback | Handler\Base::fallback() |
Minimal 500 response and native error_log() when exception processing
fails.
|
Early bootstrap error handling
ErrorHandlingBootstrap::boot() initializes error reporting and registers handlers before
the
Core is available. It sets error_reporting(E_ALL), enables PHP error logging, and
controls
display_errors and display_startup_errors using
APPNETOS_DEBUG.
Early errors are written to APPNETOS_VAR/log/error.log (normally
var/log/error.log). The bootstrap handler logs reportable PHP errors and uncaught
exceptions. It also checks fatal shutdown errors of types E_ERROR, E_PARSE,
E_CORE_ERROR and E_COMPILE_ERROR. Browser failures return HTTP 500; CLI
output
is plain text.
After the Core handler has taken ownership, the bootstrap layer is informed through ErrorHandlingBootstrap::handoverToCore().
The previously registered PHP shutdown callback cannot be unregistered, so it becomes inactive. This
prevents duplicate fatal-error handling between the two stages.
Structured APPNETOS exceptions
Core\Exception\Base extends PHP's Exception. In addition to the native
message,
code and previous throwable, it stores a structured context array and an optional
safeMessage.
Technical messages can therefore be retained for diagnostics without exposing them to users in
production.
| Public method | Description |
|---|---|
getType(): string |
Fully qualified exception class name. |
getShortType(): string |
Exception class name without namespace. |
getContext(): array |
Structured diagnostic context. |
setContext(array $context): static |
Replace context; returns the exception. |
addContext(string $key, mixed $value): static |
Add or overwrite one context entry. |
getSafeMessage(): string |
Public message or the default An internal error occurred. |
setSafeMessage(?string $message): static |
Set a safe public message. |
toArray(bool $debug = false): array |
Serialize safe metadata or detailed diagnostics. |
Factory methods
APPNETOS favors named factory methods for domain-specific exception states. For example, RegistryException
offers notAllowed(), notFound(), createFailed(), invalidClass(),
typeMismatch() and methodNotFound(). These factories supply consistent
technical messages, context and safe public messages.
use Core\Exception\RegistryException;
throw RegistryException::notFound(
$class,
$resolvedClass,
);
Factory methods are a development convention, not an enforced feature of
Core\Exception\Base.
The provided generic NotFoundException, UnauthorizedException, ForbiddenException
and ValidationException are currently semantic subclasses without their own factories.
Custom exception example
namespace Application\Exception;
use Core\Exception\Base;
class ImportException extends Base
{
public static function invalidSource(string $source): static
{
return new static(
message: 'Unsupported import source: ' . $source,
context: ['source' => $source, 'reason' => 'invalid_source'],
safeMessage: 'The import could not be processed.',
);
}
}
throw ImportException::invalidSource('unknown');
Custom exception types are handled as HTTP 500 unless the central handler is extended to map them differently.
HTTP exception classification
| Exception type | Status | HTTP title |
|---|---|---|
ValidationException |
400 | Bad Request |
UnauthorizedException |
401 | Unauthorized |
ForbiddenException |
403 | Forbidden |
NotFoundException |
404 | Not Found |
RegistryException, other exceptions and errors |
500 | Internal Server Error |
These mappings apply to the central Core exception handler. The bootstrap handler uses HTTP 500 for
terminal bootstrap failures. The handler also knows the title Unprocessable Entity for
status 422, but the provided exception-to-status mapping does not currently produce 422.
Central exception processing
Core\Exception\Handler\Base::init() registers set_exception_handler(),
set_error_handler()
and register_shutdown_function() once. Reportable PHP errors are converted to ErrorException;
fatal shutdown errors are examined with error_get_last().
- Ignore responses already sent and detect duplicate throwable signatures.
- Prevent recursive handling while the handler is active.
- Write the full error, stack trace, previous exception and APPNETOS context to
Core\Log, falling back to PHPerror_log(). - Forward the throwable to
Core\Debug::addException()when available. - Discard removable output buffers before emitting a standalone error response.
- Determine the HTTP status and select JSON problem details or native HTML.
- Use a minimal native fallback if the handler or renderer itself fails.
The duplicate signature is a SHA-256 hash of throwable class, message, file and line. Output buffers that PHP does not permit to remove cannot be forcibly discarded; already transmitted output cannot be retracted.
Core\Exception\Handler\Base::handleShutdown()
is PHP fatal-error detection. It is not the same feature as developer-defined callbacks
registered
through Core\Shutdown or #[Shutdown].
HTML and JSON responses
Standalone HTML
Core\Exception\Handler\Render\Base generates complete HTML documents with embedded CSS,
without Twig, the ordinary rendering pipeline or response controllers. Production pages contain the
status, title and safe public message. Debug pages additionally show class, message, file, line,
context, previous throwable, stack trace and selected request/runtime information. Dynamic values
are
HTML-escaped.
Problem Details JSON
The handler responds with Content-Type: application/problem+json; charset=utf-8 when the
request signals JSON through Accept, Content-Type or X-Requested-With:
XMLHttpRequest. The response follows the RFC 7807-style fields type,
title, status, detail and instance.
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "An internal error occurred.",
"instance": "/example/resource"
}
The example uses the default safe message of Core\Exception\Base. Applications can
provide a
more specific safe message. In debug mode, the handler adds a debug object containing
class, message, source location, trace and available context/previous-exception information.
AJAX compatibility note: The provided handler does not explicitly inspect the
APPNETOS-specific X-Appnetos-Ajax header. Ensure AJAX clients send a recognized JSON
Accept
header or X-Requested-With: XMLHttpRequest if JSON errors are required.
Final fallback and operational safety
If normal Core exception processing fails, the handler writes to native error_log() and
emits a minimal HTTP 500 response. Debug mode may include the handler failure and original
exception;
production mode uses a generic message. When headers are already sent, the handler can only append
escaped output.
Debug output may expose file paths, stack traces, exception context, request metadata and application internals. Configure debug mode through the environment or its override and disable it immediately after investigation. Follow the Debug documentation for removal of published DebugBar assets.
Exception logging remains active without DebugBar. Treat structured context as sensitive: do not attach credentials, tokens or personal data unnecessarily. The renderer is independent of the usual rendering services, but the Core handler still attempts to resolve it through the Registry before using its native fallback.