The ErrorPageHandler
class in JiFramework is responsible for rendering user-friendly error pages and JSON error responses when HTTP errors occur. It determines whether to display an HTML error page or a JSON response based on the client's request headers, making it suitable for both web applications and API endpoints.
This class follows the Singleton pattern to ensure only one instance is used throughout the application. It provides default error messages for common HTTP status codes but also allows custom messages to be displayed.
Method: getInstance(): ErrorPageHandler
Description: Retrieves the singleton instance of the ErrorPageHandler
class. This ensures that the same instance is used throughout the application, following the Singleton design pattern.
Parameters: None
Returns: An instance of ErrorPageHandler
.
Usage:
use JIFramework\Core\App\App;
// Initialize the App
$app = new App();
// Get the singleton instance
$errorPageHandler = $app->errorPageHandler;
OR
use JIFramework\Core\Error\ErrorPageHandler;
// Get the singleton instance
$errorPageHandler = ErrorPageHandler::getInstance();
Explanation:
- The
getInstance
method checks if an instance already exists. - If not, it creates a new instance by calling the private constructor.
- This pattern ensures that only one instance of
ErrorPageHandler
exists, promoting efficient resource usage.
Method: handle(int $errorCode, string $message = null): void
Description: Handles an HTTP error by setting the appropriate HTTP status code and rendering an error page or JSON response based on the client's request.
Parameters:
- $errorCode (
int
): The HTTP status code representing the error (e.g.,404
,500
). - $message (
string
, optional): A custom error message to display. If not provided, a default message corresponding to the status code is used.
Returns: void
Usage:
// Handle a 404 Not Found error
$errorPageHandler->handle(404);
// Handle a 500 Internal Server Error with a custom message
$errorPageHandler->handle(500, 'An unexpected error occurred. Please try again later.');
Explanation:
- The
handle
method: - Sets the HTTP response code using
http_response_code($errorCode)
. - Determines the appropriate error message to display:
- If
$message
is provided, it uses that. - Otherwise, it looks up the default message for the provided
$errorCode
. - If no default message exists, it uses a generic message.
- Checks if the client expects a JSON response by calling
isJsonRequest()
. - If so, it calls
renderJsonError()
to output a JSON response. - Otherwise, it calls
renderHtmlError()
to display an HTML error page. - The method terminates the script execution using
exit
after rendering the error response to prevent any further output.