Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments: 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

Error Handling in REST APIs Using Pure PHP

Error Handling in REST APIs Using Pure PHP

Building a REST API in core PHP gives you full control — but also puts you in charge of managing errors gracefully. Without proper error handling, your API can return confusing, insecure, or unhelpful responses to clients.

This guide shows you how to implement error handling in a pure PHP REST API step by step.


Why Proper Error Handling Matters

  • 🔐 Security: Avoid leaking stack traces or server paths.
  • 📱 Client Clarity: Let clients know what went wrong and why.
  • 🛠️ Debugging: Make logging easy without affecting user-facing responses.
  • 🌐 Standards: Follow REST best practices (status codes, JSON errors).

Common Types of API Errors

  • (400) Validation Error: Missing or invalid parameters
  • (401) Unauthorized: Invalid or missing credentials
  • (403) Forbidden: Authenticated, but not allowed
  • (404) Not Found: Endpoint or resource not found
  • (405) Method Not Allowed: HTTP method is not supported
  • (500) Server Error: Internal error occurred

Step 1: Set JSON Response Type Globally

header("Content-Type: application/json");

Place this at the top of your entry file (e.g., index.php) to ensure all responses are in JSON.


Step 2: Handle Invalid Routes

if ($uri[0] !== 'api' || $uri[1] !== 'users') {
    http_response_code(404);
    echo json_encode(['error' => 'Endpoint not found']);
    exit;
}


Step 3: Catch Internal Errors (Try-Catch)

Wrap database and processing logic in try-catch blocks:

try {
    $db = connectDB();
    $controller = new UserController($db);
    echo $controller->getAllUsers();
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
    // Log error to file: error_log($e->getMessage());
}


Step 4: Validation Error Example

if (empty($data['name']) || empty($data['email'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Name and Email are required']);
    exit;
}


Step 5: Standardized Error Responses

Create a reusable helper function:

function respondWithError($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['error' => $message]);
    exit;
}

// Usage
if (!$user) respondWithError("User not found", 404);


Step 6: Enable Logging (for Developers Only)

error_log("[ERROR] " . date('Y-m-d H:i:s') . " - " . $e->getMessage());

You can log errors to a file using PHP’s error_log() function. Never expose them in production.


Step 7: Bonus - Catch Uncaught Exceptions Globally

At the top of index.php:

set_exception_handler(function ($e) {
    http_response_code(500);
    echo json_encode(['error' => 'Unexpected server error']);
    error_log($e->getMessage());
});


Example: Full Error-Proof Request

try {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!$data) {
        respondWithError("Invalid JSON payload", 400);
    }

    // Your business logic

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Unexpected error']);
    error_log($e->getMessage());
}


Final Tips:

  • Never return raw error messages or SQL traces in production
  • Always return valid JSON and proper status codes
  • Document your error formats for API consumers

Summary:

Error handling in pure PHP REST APIs isn’t hard — but it’s essential. With a few helper functions and HTTP standards, you can make your API much more stable, developer-friendly, and secure.

Want this plugged into your existing API structure? Let me know — I’ll adjust the code to fit your use case.


PHP Rest Apis Error Handling in Apis Error handling in Rest Apis Types of Api Errors

advertisement