干掉你的 try-catch:这 3 种异常处理方式优雅 10 倍
一、引言 你是否厌倦了这样的代码? public User getUserById(Long id) { try { User user = userRepository.findById(id); if (user == null) { throw new RuntimeException("用户不存在"); } return user; } catch (Exception e) { log.error("查询用户失败", e); throw new RuntimeException("系统错误"); } } 满屏的 try-catch 不仅丑陋,而且分散了业务逻辑的注意力。今天我要分享三种优雅的异常处理方式,让你的代码焕然一新。 二、方案一:@ControllerAdvice + @ExceptionHandler 2.1 全局异常统一处理 @ControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(Globa....