通过@ControllerAdvice和@ExceptionHandler实现全局异常处理,结合自定义异常类与ResponseStatus注解,统一返回结构化响应,提升代码可维护性与用户体验。
在Java开发中,特别是在使用Spring或Spring Boot框架时,实现全局异常统一处理可以有效提升代码的可维护性和用户体验。通过集中处理异常,避免重复的try-catch代码,同时能统一返回格式,便于前端解析。
这是Spring提供的最常用方式,通过定义一个被@ControllerAdvice注解的类,配合@ExceptionHandler来捕获控制器中抛出的异常。
示例代码:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(NullPointerException.class) public ResponseEntity<String> handleNullPointer(NullPointerException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("发生了空指针异常:" + e.getMessage()); } @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("参数错误:" + e.getMessage()); } @ExceptionHandler(Exception.class) public ResponseEntity<Map<String, Object>> handleGeneralException(Exception e) { Map<String, Object> response = new HashMap<>(); response.put("error", "服务器内部错误"); response.put("message", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } }
这个类会拦截所有Controller中抛出的指定异常,并返回结构化的响应结果。
立即学习“Java免费学习笔记(深入)”;
为了更清晰地区分系统异常和业务异常,建议定义自己的异常类。
public class BusinessException extends RuntimeException { public BusinessException(String message) { super(message); } }
在业务逻辑中直接抛出:
if (user == null) { throw new BusinessException("用户不存在"); }
然后在GlobalExceptionHandler中添加对应处理方法:
@ExceptionHandler(BusinessException.class) public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) { Map<String, Object> response = new HashMap<>(); response.put("error", "业务异常"); response.put("message", e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); }
可以在自定义异常上使用@ResponseStatus注解,直接指定HTTP状态码,减少在ExceptionHandler中的重复配置。
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "用户未找到") public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
这样当该异常被抛出时,Spring会自动返回404状态码,无需额外在ControllerAdvice中写处理逻辑(除非需要定制返回体)。
基本上就这些。通过@ControllerAdvice统一捕获异常,配合自定义异常类和合理的返回结构,就能实现清晰、可维护的全局异常处理机制。不复杂但容易忽略细节。
以上就是在Java中如何实现全局异常统一处理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号