Exception Messages and Codes
The Exception constructor accepts a message string, a numeric code, and a previous exception for chaining. These help with logging and error identification.
The Exception constructor accepts a message string, a numeric code, and a previous exception for chaining. These help with logging and error identification.
<?php
try {
throw new RuntimeException("Database connection failed", 503);
} catch (RuntimeException $e) {
echo $e->getMessage(); // "Database connection failed"
echo $e->getCode(); // 503
echo $e->getFile(); // Path to the file
echo $e->getLine(); // Line number
echo $e->getTraceAsString(); // Stack trace
// For API responses
http_response_code($e->getCode());
echo json_encode(["error" => $e->getMessage()]);
}
Use HTTP status codes as exception codes for API exceptions — makes it easy to map exceptions to HTTP responses.