In PHP REST APIs, how do I gracefully handle failures?

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()); } ?>

PHP REST API error handling graceful failure API response