In PHP REST APIs, gracefully handling failures is crucial for providing a good user experience and ensuring the stability of your application. Below is an example that demonstrates how to implement error handling in your PHP REST API.
<?php
class ApiResponse {
public static function success($data) {
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => $data]);
exit();
}
public static function error($message, $code = 500) {
http_response_code($code);
header('Content-Type: application/json');
echo json_encode(['status' => 'error', 'message' => $message]);
exit();
}
}
// Example usage
try {
// Simulating an operation that could fail
if (!isset($_GET['id'])) {
throw new Exception('ID parameter is missing', 400);
}
// Assuming we fetch data here...
// If data fetch fails
// throw new Exception('Database connection error', 500);
// If successful
ApiResponse::success(['item' => 'Some data based on ID']);
} catch (Exception $e) {
ApiResponse::error($e->getMessage(), $e->getCode());
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?