DEV Community

Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

php Error handling & debugging

basic of Error Handling Summary
php basic error list

error_reporting(E_ALL); // Show all errors
ini_set('display_errors', 1);

Enter fullscreen mode Exit fullscreen mode
  • Exceptions in PHP Exceptions provide a structured way to handle errors without scattering if checks everywhere.
try {
    // Code that may throw an exception
    throw new Exception("Something went wrong!");
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
} finally {
    echo "This will run no matter what.";
}

Enter fullscreen mode Exit fullscreen mode
  • Custom Exceptions You can create your own exception classes for specific scenarios.
class InsufficientFundsException extends Exception {}

function withdraw($balance, $amount) {
    if ($amount > $balance) {
        throw new InsufficientFundsException("Not enough balance to withdraw $amount");
    }
    return $balance - $amount;
}

try {
    $newBalance = withdraw(100, 150);
} catch (InsufficientFundsException $e) {
    echo "Custom Error: " . $e->getMessage();
} finally {
    echo " - Transaction attempted.";
}

Enter fullscreen mode Exit fullscreen mode

you should try this custom exception by yourself for better understanding and debugging

Here’s a small script that intentionally throws exceptions:

class NegativeNumberException extends Exception {}
class DivisionByZeroCustomException extends Exception {}

function processNumber($num) {
    if ($num < 0) {
        throw new NegativeNumberException("Negative number detected: $num");
    }
    if ($num === 0) {
        throw new DivisionByZeroCustomException("Cannot divide by zero!");
    }
    return 100 / $num;
}

$numbers = [10, 0, -5, 25];

foreach ($numbers as $num) {
    try {
        echo "Result: " . processNumber($num) . PHP_EOL;
    } catch (NegativeNumberException $e) {
        echo "Negative error: " . $e->getMessage() . PHP_EOL;
    } catch (DivisionByZeroCustomException $e) {
        echo "Zero error: " . $e->getMessage() . PHP_EOL;
    } catch (Exception $e) {
        echo "Other error: " . $e->getMessage() . PHP_EOL;
    } finally {
        echo "Processed number: $num" . PHP_EOL;
    }
}

Enter fullscreen mode Exit fullscreen mode
  • Debugging in Production Without Tools When you can’t install tools like Xdebug or Laravel Telescope, you can still debug with plain PHP.
ini_set('display_errors', 0); // Hide from browser
ini_set('log_errors', 1); // Enable logging
ini_set('error_log', __DIR__ . '/error.log'); // Custom log file

// Example: force an error
file_get_contents("non_existing_file.txt");

Enter fullscreen mode Exit fullscreen mode
  • For debugging API's in production for testing specific api or logic we can implements or use headers for debugging by passign headers like customedebug: 'true'
// Example API logic
try {
    $data = [
        'user' => 'Ahmed',
        'role' => 'Admin',
        'time' => date('Y-m-d H:i:s')
    ];

    // Intentionally trigger some debug output only if debug mode is ON
    if ($isDebug) {
        $data['debug_info'] = [
            'memory_usage' => memory_get_usage(),
            'php_version'  => PHP_VERSION,
            'env'          => 'production', // Still production, but we expose it
            'trace'        => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)
        ];
    }

    echo json_encode([
        'status' => 'success',
        'data'   => $data
    ]);

} catch (Exception $e) {
    // Always log real errors
    error_log("API Error: " . $e->getMessage());

    $response = ['status' => 'error', 'message' => 'Something went wrong'];

    // Only expose full message in debug mode
    if ($isDebug) {
        $response['exception'] = $e->getMessage();
    }

    echo json_encode($response);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)