Performing error handling and logging in PHP functions is critical to ensure the stability and maintainability of your application. Error handling uses try-catch blocks to catch errors and can handle them by throwing exceptions. Logging uses the error_log() function to log error information to a log file for debugging purposes. The practical case shows how to use try-catch and error_log() for error handling and logging in the calculateAverage function.
Error handling and logging in PHP functions
Error handling and logging in PHP functions ensure that the application Key to stability and maintainability.
Error handling
Use try
and catch
blocks to catch errors in functions:
function divide($num1, $num2) { try { $result = $num1 / $num2; } catch (DivisionByZeroError $e) { // 如果除以零,则处理错误 throw new Exception("Division by zero"); } return $result; }
Logging
Use PHP function error_log()
Record error information to the log file:
function logError($message, $file, $line) { error_log("[$file, line $line]: $message", 3, "error.log"); }
Actual case:
Consider the "calculateAverage" function to compute the average of numbers:
function calculateAverage(...$numbers) { try { if (count($numbers) === 0) { throw new Exception('No numbers provided'); } $sum = 0; foreach ($numbers as $num) { if (!is_numeric($num)) { throw new TypeError('Not all elements are numeric'); } $sum += $num; } return $sum / count($numbers); } catch (Exception $e) { logError($e->getMessage(), __FILE__, __LINE__); throw $e; } }
When this function is called, if the argument is invalid, it will log an error message and throw an exception.
Notes
set_error_handler()
to customize error handling. The above is the detailed content of How to do error handling and logging in PHP functions?. For more information, please follow other related articles on the PHP Chinese website!