Consistent API Errors: Exceptions and Response Format
Return consistent API error responses using custom exceptions and centralized handlers.
APIs should return predictable errors so frontend and mobile clients can handle them correctly. A common professional format: ```json { "error": { "code": "OUT_OF_STOCK", "message": "This item is no longer available." } } ``` ## Create a custom exception ```php class OutOfStockException extends Exception { public function render() { return response()->json([ 'error' => [ 'code' => 'OUT_OF_STOCK', 'message' => $this->getMessage(), ], ], 409); } } ``` ## Use it ```php if ($product->stock <= 0) { throw new OutOfStockException('This item is no longer available.'); } ``` ## Graph: centralized error handling ```mermaid flowchart LR A[Service/Controller throws] --> B[Exception Handler] B --> C[Standard JSON Error] C --> D[Client] ``` In the next tutorial, we will implement API request validation using form requests for APIs.