异常捕获
try {
if (!file_exists('config.php')) {
throw new Exception('配置文件不存在', 1001);
}
$config = require 'config.php';
} catch (Exception $e) {
echo "错误码: " . $e->getCode();
echo "错误信息: " . $e->getMessage();
echo "文件: " . $e->getFile() . " 行: " . $e->getLine();
// 记录日志
error_log($e->getTraceAsString());
} finally {
// 无论是否异常都会执行
echo "执行完毕";
}自定义异常
class DatabaseException extends Exception {}
class ValidationException extends Exception {}
// 根据类型处理
try {
// ...
} catch (ValidationException $e) {
// 返回验证错误给前端
http_response_code(422);
echo json_encode(['errors' => $e->getMessage()]);
} catch (DatabaseException $e) {
// 报警
error_log("DB Error: " . $e->getMessage());
http_response_code(500);
}全局异常处理(Laravel)
在 App\Exceptions\Handler 中:
public function register() {
$this->reportable(function (Throwable $e) {
if ($e instanceof DatabaseException) {
// 发送到 Sentry
}
});
}日志推荐
- 使用
Monolog输出到文件、邮箱、或 ELK - 生产环境记录
error级别,开发环境记录debug - 敏感信息(密码)脱敏后再记录
良好的异常处理能提前预防线上事故。
