欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

PHP 异常处理与错误日志最佳实践

时间:2026年08月12日 05:38:48 浏览:0

PHP 异常处理与错误日志最佳实践


优雅的异常处理能提升应用健壮性。


1. try-catch 结构


try {
if (!file_exists('config.php')) {
throw new Exception('配置文件不存在', 1001);
}
$config = require 'config.php';
} catch (Exception $e) {
error_log($e->getMessage());
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
} finally {
// 总会执行
}

2. 自定义异常


class ValidationException extends Exception {}

// 根据不同异常类型处理
try {
// ...
} catch (ValidationException $e) {
http_response_code(422);
} catch (DatabaseException $e) {
http_response_code(500);
// 记录详细日志
}

3. 全局异常处理器(Laravel)


App\Exceptions\Handler 中:


public function register() {
$this->reportable(function (Throwable $e) {
if ($e instanceof DatabaseException) {
// 发送报警
}
});
}

4. 日志记录



  • 使用 Monolog 输出到文件或外部服务。

  • 敏感信息脱敏。


良好的异常处理是应用稳定的保障。