PHP offers several layers of error handling — from global error reporting settings to exceptions and custom handlers.
// Development — show everything
error_reporting(E_ALL);
ini_set("display_errors", "1");
// Production — log, never display
error_reporting(E_ALL);
ini_set("display_errors", "0");
ini_set("log_errors", "1");
ini_set("error_log", "/var/log/php_errors.log");
try {
$pdo = new PDO("mysql:host=localhost;dbname=app", "root", "");
// risky operations...
} catch (PDOException $e) {
echo "DB Error: " . $e->getMessage();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Cleanup always runs.";
}
function divide(int $a, int $b): float {
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
echo divide(10, 2); // 5
echo divide(10, 0); // throws exception
set_exception_handler(function (Throwable $e) {
http_response_code(500);
error_log($e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
echo "Something went wrong. Please try again later.";
});