PHP Try and Catch: A Complete Guide to Error Handling in Local and Production
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.
1. What is Try and Catch?
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.
2. Error Handling in Local (Development Environment)
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.
3. Error Handling in Production
In production, things change:
- Users should never see raw error details.
- You should log errors privately.
- The user should only see a friendly message.
// 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.
4. Example: Handling API Failures
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.";
}
5. Custom Exception Classes
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.
6. Bonus: Global Error Handling
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.
7. Local vs Production Cheat Sheet
| Environment | Display Errors | Log Errors | User Message |
|---|---|---|---|
| Local (Dev) | ✅ Yes | Optional | Debug Info |
| Production | ❌ No | ✅ Yes | Friendly Msg |
Pro Tips
- Use
.envfiles to toggle betweenAPP_ENV=localandAPP_ENV=production. - Always log errors in a secure, non-public folder.
- Frameworks like Laravel and Symfony already handle this out of the box.
Quick FAQ
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.
Final Thoughts
Error handling is about balance.
- In local, be noisy—show all errors.
- In production, be quiet—log errors and show polite messages.
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?
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.