Skip to content
PHP Logo

How can one ensure that errors within the catch block, such as file operations, are properly logged in PHP?

To ensure that errors within the catch block, such as file operations, are properly logged in PHP, you can use the error_log function to log the error message to a specified file. This allows you to track and troubleshoot any issues that may occur during file operations. Additionally, you can include relevant information about the error, such as the timestamp and the file being operated on, to aid in debugging.

php
try {
    // File operation code here
} catch (Exception $e) {
    $error_message = "Error: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine();
    error_log($error_message, 3, "error.log");
}