Spring Boot异常处理与调试技巧实战指南

一、异常处理的艺术

1. @ControllerAdvice全局异常处理

在Spring Boot中,@ControllerAdvice是实现全局异常处理的利器。它能够拦截所有控制器抛出的异常,进行统一处理。

@ControllerAdvice
public class GlobalExceptionHandler {
    
    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex) {
        ErrorResponse response = new ErrorResponse(
            ex.getErrorCode(), 
            ex.getMessage(),
            System.currentTimeMillis()
        );
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
    
    // 处理所有未捕获异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex) {
        ErrorResponse response = new ErrorResponse(
            "500", 
            "服务器内部错误",
            System.currentTimeMillis()
        );
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

实践建议

  • 为不同异常类型创建专门的处理器方法
  • 返回结构化的错误信息(如JSON格式)
  • 记录异常日志以便后续排查

2. 自定义错误页面

Spring Boot默认提供了/error映射,我们可以自定义错误页面来提升用户体验:

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());
            
            if(statusCode == HttpStatus.NOT_FOUND.value()) {
                return "error-404";
            } else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "error-500";
            }
        }
        return "error";
    }
}

resources/templates目录下创建对应的HTML模板文件(如error-404.html)。

实践建议

  • 为常见HTTP状态码(404、500等)设计专用页面
  • 页面应包含友好的错误提示和引导操作
  • 保持与系统整体风格一致

二、调试技巧大全

1. 自动配置报告(--debug模式)

启动应用时添加--debug参数,可以查看Spring Boot的自动配置决策过程:

java -jar your-application.jar --debug

报告会显示:

  • 匹配的自动配置类(Positive matches)
  • 排除的自动配置类(Negative matches)
  • 未处理的排除条件(Exclusions)

典型输出示例

=========================
AUTO-CONFIGURATION REPORT
=========================

Positive matches:
-----------------
   AopAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.context.annotation.EnableAspectJAutoProxy' (OnClassCondition)

Negative matches:
-----------------
   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition)

2. 日志分析技巧

Spring Boot使用Logback作为默认日志框架,合理配置日志级别能有效辅助调试:

# application.yml
logging:
  level:
    root: INFO
    org.springframework.web: DEBUG
    com.yourpackage: TRACE
  file:
    name: logs/app.log
  pattern:
    file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"

日志分析要点

  1. 请求追踪:开启org.springframework.web的DEBUG级别,查看完整请求处理流程
  2. SQL日志:配置spring.jpa.show-sql=true显示执行的SQL语句
  3. 性能分析:使用@Timed注解记录方法执行时间
@RestController
@Timed
public class MyController {
    @GetMapping("/api/data")
    @Timed(value = "get.data.time", description = "Time taken to return data")
    public ResponseEntity<?> getData() {
        // 业务逻辑
    }
}

三、实战问题排查流程

当遇到问题时,建议按照以下流程排查:

图1

常见问题速查表

问题现象可能原因解决方案
启动失败,端口占用端口被其他进程占用更改端口或终止占用进程
依赖注入失败Bean未正确扫描检查@ComponentScan范围
配置不生效配置加载顺序问题使用@PropertySource明确指定
性能下降数据库查询问题添加索引或优化查询

四、最佳实践总结

  1. 异常处理

    • 区分业务异常和系统异常
    • 为API和页面分别设计错误响应
    • 记录足够的上下文信息
  2. 调试技巧

    • 善用--debug模式分析自动配置
    • 合理配置日志级别,避免信息过载
    • 使用Actuator端点(/actuator)监控应用状态
  3. 开发建议

    • 保持异常处理代码简洁明确
    • 为关键操作添加详细日志
    • 建立标准的错误码体系

通过系统化的异常处理和科学的调试方法,可以显著提高Spring Boot应用的稳定性和可维护性。

添加新评论