PHP Error Handling Best Practices 2026: try, catch, finally, and Beyond

By Lyndon Bermoy

Updated on:

PHP Error Handling Best Practices 2026: try, catch, finally, and Beyond

Error handling is one of the most overlooked aspects of PHP development. Beginners tend to display all errors to the screen (a security risk in production) or suppress them entirely (making debugging impossible). Professional PHP applications handle errors gracefully: log them for developers, show appropriate messages to users, and never reveal sensitive system information publicly.

This guide covers the complete PHP error handling toolkit in 2026.

Display Errors: Development vs Production

The first rule of PHP error handling: never display errors to end users in production. Error messages reveal file paths, database structure, and code logic that attackers can exploit.

// Development (local environment) — show all errors:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Production — hide errors from users, log them instead:
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);  // Still report all — but to the log, not the screen
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php_errors.log');

In Laravel, this is handled automatically by the APP_DEBUG setting in your .env file: APP_DEBUG=true shows errors in development; APP_DEBUG=false hides them in production.

try / catch / finally

The try/catch block handles exceptions — objects thrown when something goes wrong that the normal flow cannot handle:

<?php
function divide(float $a, float $b): float {
    if ($b === 0.0) {
        throw new InvalidArgumentException("Division by zero is not allowed.");
    }
    return $a / $b;
}

try {
    $result = divide(10, 0);
    echo "Result: $result";  // This line never runs
} catch (InvalidArgumentException $e) {
    echo "Math error: " . $e->getMessage();
    // Log the error for developers:
    error_log("[" . date('Y-m-d H:i:s') . "] " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
} finally {
    // finally runs whether or not an exception was thrown
    echo "Calculation attempt completed.";
}

The finally block always executes — useful for cleanup operations like closing database connections or file handles, regardless of whether the operation succeeded.

READ ALSO:   PHP forms Best Practices for Beginners

Catching Multiple Exception Types

try {
    $pdo  = new PDO('mysql:host=localhost;dbname=myapp', $user, $pass);
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll();
} catch (PDOException $e) {
    // Database-specific error
    error_log("Database error: " . $e->getMessage());
    throw new RuntimeException("A database error occurred.", 500, $e);
} catch (InvalidArgumentException $e) {
    // Bad input error
    error_log("Invalid input: " . $e->getMessage());
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
} catch (\Throwable $e) {
    // Catch-all for any other error (PHP 7+)
    error_log("Unexpected error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}

PHP 7+ introduced \Throwable as a catch-all that catches both Exception and Error (which handles PHP engine errors like type errors and memory errors).

Custom Exception Classes

Create specific exception types for different error categories in your application:

// Base application exception
class AppException extends RuntimeException {}

// Specific exception types
class ValidationException extends AppException {
    private array $errors;

    public function __construct(array $errors, string $message = "Validation failed") {
        parent::__construct($message);
        $this->errors = $errors;
    }

    public function getErrors(): array {
        return $this->errors;
    }
}

class NotFoundException extends AppException {
    public function __construct(string $resource, int|string $id) {
        parent::__construct("{$resource} with ID {$id} not found.", 404);
    }
}

class UnauthorizedException extends AppException {
    public function __construct(string $message = "Unauthorized") {
        parent::__construct($message, 401);
    }
}
// Usage in a service:
function getUserById(int $id): array {
    $user = $db->find($id);
    if (!$user) {
        throw new NotFoundException('User', $id);
    }
    return $user;
}

// Usage in a controller:
try {
    $user = getUserById($id);
    echo json_encode($user);
} catch (NotFoundException $e) {
    http_response_code($e->getCode()); // 404
    echo json_encode(['error' => $e->getMessage()]);
} catch (UnauthorizedException $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Login required']);
}

Global Exception Handler

Register a global handler to catch any unhandled exceptions rather than letting PHP display raw error output:

// Register at bootstrap/app entry point:
set_exception_handler(function (\Throwable $e) {
    // Log the full exception with stack trace
    error_log(sprintf(
        "[%s] %s: %s in %s:%d\nStack trace:\n%s",
        date('Y-m-d H:i:s'),
        get_class($e),
        $e->getMessage(),
        $e->getFile(),
        $e->getLine(),
        $e->getTraceAsString()
    ));

    // Return appropriate response
    if (PHP_SAPI === 'cli') {
        echo "Error: " . $e->getMessage() . PHP_EOL;
        exit(1);
    }

    http_response_code(500);

    // In production: generic message
    // In development: full details
    if (getenv('APP_ENV') === 'production') {
        echo json_encode(['error' => 'An unexpected error occurred.']);
    } else {
        echo json_encode([
            'error'   => $e->getMessage(),
            'file'    => $e->getFile(),
            'line'    => $e->getLine(),
            'trace'   => $e->getTraceAsString(),
        ]);
    }
});

Structured Logging with Monolog

For production applications, a structured logging library like Monolog is better than raw error_log():

composer require monolog/monolog
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;

$log = new Logger('myapp');

// Write to a rotating daily log file (keeps last 30 days):
$log->pushHandler(new RotatingFileHandler('/var/log/myapp/app.log', 30, Logger::DEBUG));

// Usage:
$log->info('User logged in', ['user_id' => 42, 'ip' => $_SERVER['REMOTE_ADDR']]);
$log->warning('Rate limit approaching', ['user_id' => 42, 'requests' => 55]);
$log->error('Payment failed', ['order_id' => 123, 'error' => $e->getMessage()]);
$log->critical('Database connection lost', ['exception' => $e]);

Laravel includes Monolog pre-configured. Your application logs are at storage/logs/laravel.log and can be tailed in real time.

READ ALSO:   Git for PHP Developers: Essential Workflow Guide (2026)

Error Handling Best Practices Checklist

  • [ ] display_errors = Off in production php.ini or .htaccess
  • [ ] log_errors = On with a writable log file path
  • [ ] Global exception handler registered at application bootstrap
  • [ ] Custom exception classes for domain-specific errors (validation, auth, not found)
  • [ ] finally used for resource cleanup (database connections, file handles)
  • [ ] Error responses return correct HTTP status codes (404, 401, 422, 500)
  • [ ] Never log sensitive data (passwords, credit card numbers) in error messages
  • [ ] Stack traces and system paths never exposed in production API responses
  • [ ] Log rotation configured — error logs do not grow unbounded

Conclusion

Professional PHP error handling requires three things working together: hide errors from end users in production, log them with sufficient context for developers to debug, and return appropriate HTTP responses for different failure types. Custom exception classes, a global handler, and structured logging with Monolog cover all of these. Apply these patterns consistently and error investigation becomes manageable rather than a hunt through raw PHP warnings.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment