Kritim Yantra
Sep 06, 2025
Errors are every developer’s nightmare. Imagine this—you launch your shiny new PHP project, and suddenly users see a big, ugly error message:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]...
Not only does it look unprofessional, but it also leaks sensitive information about your database. Yikes! 😬
The good news? With try-catch and smart error handling, you can keep control of your code whether you’re coding locally or running in production. Let’s walk through it step by step.
Think of try-catch like a safety net. You try running risky code, and if it fails, you catch the error before it breaks everything.
try {
// Risky operation
$number = 10 / 0;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
👉 Instead of PHP crashing, you handle the situation gracefully.
When you’re coding locally, you want maximum visibility. Every warning, every notice—it all helps you debug faster.
// Show all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Debug Info: " . $e->getMessage();
}
✅ You see detailed messages.
✅ Perfect for fixing bugs quickly.
In production, things change:
// Hide errors from screen
error_reporting(E_ALL);
ini_set('display_errors', 0);
try {
$conn = new PDO("mysql:host=localhost;dbname=live_db", "user", "pass");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
// Log the error
error_log($e->getMessage(), 3, __DIR__ . '/logs/errors.log');
// Show friendly message
echo "Something went wrong. Please try again later 🙏";
}
👉 The customer stays calm.
👉 You still know what happened via logs.
APIs are unreliable sometimes. Here’s how you can safely deal with them:
try {
$response = file_get_contents("https://fakeapi.com/data");
if ($response === FALSE) {
throw new Exception("API request failed");
}
echo "API Data: " . $response;
} catch (Exception $e) {
error_log("API Error: " . $e->getMessage());
echo "Sorry, we couldn’t fetch data right now.";
}
You can create your own exceptions for better clarity.
class PaymentException extends Exception {}
try {
$balance = 100;
$withdraw = 200;
if ($withdraw > $balance) {
throw new PaymentException("Insufficient balance!");
}
echo "Withdrawal successful!";
} catch (PaymentException $e) {
echo "Payment Error: " . $e->getMessage();
}
👉 Makes it easier to separate database errors, API errors, and custom business logic errors.
Sometimes, you don’t want to write try-catch everywhere. Instead, you can register a global handler:
set_exception_handler(function ($e) {
error_log("Uncaught Exception: " . $e->getMessage());
echo "Oops! Something unexpected happened.";
});
Now, even uncaught exceptions are handled gracefully.
Environment | Display Errors | Log Errors | User Message |
---|---|---|---|
Local (Dev) | ✅ Yes | Optional | Debug Info |
Production | ❌ No | ✅ Yes | Friendly Msg |
.env
files to toggle between APP_ENV=local
and APP_ENV=production
.Q1: Should I use die()
or exit()
instead of try-catch?
They stop execution but don’t give flexibility. Try-catch is much better for production-grade apps.
Q2: Can I catch all PHP errors with try-catch?
Not all. For non-exception errors (like warnings), you need set_error_handler()
.
Q3: What’s better—logging to file or database?
For small apps: file logging is fine. For big apps: use database or external log services like Sentry.
Error handling is about balance.
That’s how you build applications that are both developer-friendly and user-friendly. 🚀
👉 Now I want to hear from you—how do you handle errors in your PHP projects? Do you use custom exceptions, or just log everything?
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google