AppException
render404()
render404()
This method is used to display a 404
error page when a resource is not found. It checks the debug mode and displays detailed information if debug mode is enabled; otherwise, it displays a general message.
Sets the HTTP response code to the error code (404).
If debug mode is enabled, it displays detailed error information including the error code, error message, file, line, and trace.
If debug mode is disabled, it displays a general 404 error message.
Uses the
Render
class to display the 404 error page.Stops further execution using
exit()
.
Example:
$exception = new AppException("Page not found", 0, null, 404);
$exception->handle();
renderError()
renderError()
This method is used to display exception information in HTML format for the user. It also checks the debug mode and displays detailed information if debug mode is enabled; otherwise, it displays a general message.
Sets the HTTP response code to the error code (500 or other error codes).
If debug mode is enabled, it displays detailed error information including the error code, error message, file, line, and trace.
If debug mode is disabled, it displays a general error message.
Stops further execution using
exit()
.
$exception = new AppException("Internal Server Error", 0, null, 500);
$exception->handle();
handle()
handle()
This method handles the exception, logs it, and displays the error information to the user. It checks the error status code and calls the corresponding method (render404
or renderError
).
Logs the error using the
Logger
class.Checks the error status code:
If it is 404, calls the
render404()
method.If it is another error code, calls the
renderError()
method.
Example:
try {
// Some code that may throw an exception
throw new AppException("Page not found", 0, null, 404);
} catch (AppException $e) {
$e->handle();
}
Using in Controller
<?php
namespace App\Controllers;
use System\Core\BaseController;
use System\Core\AppException;
class UserController extends BaseController {
public function index() {
try {
// Simulate an error (e.g., user not found)
$user = $this->findUserById(1);
if (!$user) {
throw new AppException('User not found!', 0, null, 404);
}
// Render the user data
$this->render('user/profile', ['user' => $user]);
} catch (AppException $e) {
// Handle the exception
$e->handle();
}
}
private function findUserById($id) {
// Sample method to simulate user fetching; returns null to simulate "user not found"
return null;
}
}
How It Works:
try {}
→ Starts the error-handling block.Attempts to find the user using
findUserById(1)
.If the user is not found (
null
), throws an AppException with the message"User not found!"
and error code404
.If no error occurs, renders the user profile page using
render('user/profile', ['user' => $user])
.catch (AppException $e) {}
→ If an error occurs, it is handled by calling$e->handle();
, which may log the error or display an error page.
Last updated
Was this helpful?