使用@ControllerAdvice和@ExceptionHandler实现Web层全局异常处理,结合自定义异常与日志框架;多线程环境通过Thread.UncaughtExceptionHandler捕获未处理异常,提升系统稳定性与可维护性。
在Java中实现全局异常处理,主要是为了集中管理程序运行过程中未被捕获的异常,避免程序因异常而崩溃,同时提升代码的可维护性和用户体验。通过合理设计,可以统一记录日志、返回友好提示或执行清理操作。
@ControllerAdvice
和@ExceptionHandler注解来实现全局异常处理。
步骤如下:
@ControllerAdvice注解,该类将作用于所有控制器。@ExceptionHandler方法,分别处理不同类型的异常。@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity handleNullPointer(NullPointerException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("发生了空指针异常:" + e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity handleIllegalArgument(IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("参数错误:" + e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity handleGeneralException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("服务器内部错误:" + e.getMessage());
}
}
自定义异常示例:
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
在全局异常处理器中添加对应处理方法:
@ExceptionHandler(UserNotFoundException.class) public ResponseEntity
Thread.UncaughtExceptionHandler来捕获未处理的线程异常。
设置默认异常处理器:
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println("线程 " + t.getName() + " 发生未捕获异常: " + e.getMessage());
// 可以记录日志或发送告警
}
}
// 使用方式
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
例如在异常处理方法中加入日志记录:
@Autowired private Logger logger; @ExceptionHandler(Exception.class) public ResponseEntityhandleGeneralException(Exception e) { logger.error("未预期的异常发生:", e); // 记录堆栈信息 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("系统繁忙,请稍后重试"); }
基本上就这些。根据项目类型选择合适的全局异常处理方式,Web应用优先用@ControllerAdvice,多线程环境注意设置线程异常处理器,再配合日志输出,就能有效掌控系统的异常行为。