Error Handling
Errors will happen. The goal is to show visitors a calm page, give developers enough detail to fix the problem, and avoid leaking internals to the public.
Environments change the behaviour
In development, CodeIgniter shows detailed exception pages and the debug toolbar. In production, those details are hidden and the error is written to the logs.
CI_ENVIRONMENT = production
Custom error pages
Create templates under app/Views/errors/html, for example error_404.php and error_production.php. Keep them simple, include a link home, and match the site design.
Throw the right exception
use CodeIgniter\Exceptions\PageNotFoundException;
if ($product === null) {
throw PageNotFoundException::forPageNotFound();
}
Log useful context
log_message() writes to writable/logs and accepts the standard levels: debug, info, notice, warning, error, critical, alert, and emergency.
log_message('error', 'Payment failed for order {order}', ['order' => $orderId]);
Log identifiers and outcomes, never passwords, card numbers, or session values.
Handle database failures
Check the result of transactions and roll back when a step fails. Returning a generic failure message is better than leaving partial data behind or exposing SQL errors.
Do not swallow exceptions
Catching an exception only to ignore it hides bugs. Handle it meaningfully, rethrow it, or log it and return a useful response.
Production checklist
- Detailed errors disabled.
- Log directory writable and rotated.
- Alerts for repeated critical errors.
- Custom 404 and 500 pages tested.
- No debug output committed to templates.