Java CheckFailedException会去获取message.properties的内容吗

CheckFailedException是 Java 中一个自定义异常类,通常不会自动获取message.properties文件的内容,除非在代码中显式实现了国际化消息加载。

常见的实现方式:

1. 手动加载资源文件

复制代码
public class CheckFailedException extends RuntimeException {
    public CheckFailedException(String messageKey, Locale locale) {
        super(loadMessage(messageKey, locale));
    }
    
    private static String loadMessage(String key, Locale locale) {
        ResourceBundle bundle = ResourceBundle.getBundle("message", locale);
        return bundle.getString(key);
    }
}

2. 通过框架支持(如 Spring)

  • 在 Spring 中,可以使用 MessageSource

    @Component
    public class ExceptionService {
    @Autowired
    private MessageSource messageSource;

    复制代码
      public void throwCheckFailed(String messageKey, Object[] args) {
          String message = messageSource.getMessage(
              messageKey, 
              args, 
              LocaleContextHolder.getLocale()
          );
          throw new CheckFailedException(message);
      }

    }

3. 简单实现(不推荐)

复制代码
// 直接传递消息,不自动获取properties
throw new CheckFailedException("error.user.not.found");

判断是否自动获取:

  1. 查看异常类定义 :检查 CheckFailedException的构造函数

  2. 查看项目配置:检查是否有相关的国际化配置

  3. 查看框架集成:是否使用了 Spring、Quarkus 等框架的消息机制

建议做法:

复制代码
// 推荐:在业务层处理消息,异常只负责携带
public class BusinessService {
    @Autowired
    private MessageSource messageSource;
    
    public void checkSomething() {
        if (conditionFailed) {
            String errorMsg = messageSource.getMessage(
                "check.failed.error", 
                null, 
                Locale.getDefault()
            );
            throw new CheckFailedException(errorMsg);
        }
    }
}

总结 :标准的 CheckFailedException不会自动获取 message.properties,除非你的项目特别实现了这个功能。通常需要在抛出异常前先获取消息文本。

相关推荐
源代码•宸7 分钟前
GoLang八股(Go语言基础)
开发语言·后端·golang·map·defer·recover·panic
czlczl200209257 分钟前
OAuth 2.0 解析:后端开发者视角的原理与流程讲解
java·spring boot·后端
颜淡慕潇15 分钟前
Spring Boot 3.3.x、3.4.x、3.5.x 深度对比与演进分析
java·后端·架构
rit843249916 分钟前
基于MATLAB的SUSAN特征检测算子边缘提取实现
开发语言·matlab
g***557518 分钟前
Java高级开发进阶教程之系列
java·开发语言
鲁正杰26 分钟前
【运维部署】现代化内网穿透与文件共享方案 (Rust)
运维·开发语言·rust
阿达King哥28 分钟前
在Windows11下编译openjdk 21
java·jvm
shark-chili1 小时前
从操作系统底层浅谈程序栈的高效性
java
2401_876907521 小时前
USB TYPE-C 公头连接器设计规范总结:提升可靠性、降本增效的关键指南
c语言·开发语言·设计规范
额呃呃1 小时前
std::allocator<T>::destroy
开发语言