What are the best practices for handling HTTP status codes like 404 and 500 in PHP to ensure proper error handling?
When handling HTTP status codes like 404 and 500 in PHP, it is important to properly handle these errors to provide a better user experience. One common practice is to use try-catch blocks to catch exceptions and display a custom error message or redirect users to a specific error page based on the status code.
try {
// Your code that may throw exceptions
} catch (Exception $e) {
$statusCode = http_response_code();
if ($statusCode == 404) {
// Handle 404 error
echo "404 Not Found";
} elseif ($statusCode == 500) {
// Handle 500 error
echo "500 Internal Server Error";
} else {
// Handle other errors
echo "An error occurred";
}
}