定义CustomException类继承RuntimeException,用于封装业务异常;在业务逻辑中根据规则抛出带错误码的BusinessException;通过@ControllerAdvice和@ExceptionHandler实现全局捕获并返回结构化JSON;可选结合MessageSource支持国际化。

在Java开发中,为了更清晰地表达业务逻辑中的异常情况,通常会通过自定义异常类(CustomException)来处理业务异常。相比直接使用系统内置异常(如RuntimeException),自定义异常能提高代码可读性、便于维护,并支持携带更丰富的错误信息。
创建一个继承自Exception或RuntimeException的自定义异常类。如果希望强制调用方处理异常,应继承Exception;若为运行时异常,可继承RuntimeException。
public class BusinessException extends RuntimeException {
private String errorCode;
public BusinessException(String message) {
super(message);
}
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}在服务层或业务方法中,根据具体业务规则判断是否需要中断流程并抛出异常。
示例:用户注册时检查用户名唯一性public class UserService {
private UserRepository userRepository;
public void registerUser(String username, String password) {
if (username == null || username.trim().isEmpty()) {
throw new BusinessException("INVALID_USERNAME", "用户名不能为空");
}
if (userRepository.existsByUsername(username)) {
throw new BusinessException("USERNAME_EXISTS", "该用户名已被占用");
}
// 执行注册逻辑
User user = new User(username, password);
userRepository.save(user);
}
}结合Spring框架的@ControllerAdvice和@ExceptionHandler实现全局异常捕获,避免异常信息直接暴露给前端。
立即学习“Java免费学习笔记(深入)”;
示例:全局异常处理器@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) {
Map<String, Object> response = new HashMap<>();
response.put("success", false);
response.put("message", e.getMessage());
response.put("error_code", e.getErrorCode());
response.put("timestamp", System.currentTimeMillis());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
}这样,当任何控制器中抛出BusinessException时,都会被统一拦截并返回结构化JSON响应。
为提升系统健壮性和多语言支持能力,可以将错误码与资源文件关联。例如:
messages_zh_CN.properties
USERNAME_EXISTS=该用户名已被占用
结合MessageSource在异常处理器中动态获取提示信息。
基本上就这些。通过定义CustomException并在业务中合理抛出,配合统一处理机制,能够有效管理Java应用中的业务异常,提升用户体验和系统可维护性。
以上就是在Java中如何使用CustomException实现业务逻辑异常处理_业务异常处理方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号