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,除非你的项目特别实现了这个功能。通常需要在抛出异常前先获取消息文本。

相关推荐
云创智城-yuncitys5 分钟前
YunParking 4.0:JDK 17 与 Spring Boot 3.2 的停车云升级
java·开发语言·spring boot
文丑颜不良啊7 分钟前
LeetCode1661~1680题目解析
java·leetcode
子非鱼@Itfuture9 分钟前
关于前后端联调中登录状态/登录信息失效?
java·前端
郭小李10 分钟前
openFeign入门
java·开发语言·前端
wljt35 分钟前
公司二-面试题
java·开发语言·mybatis
AI备案指南-满满1 小时前
算法备案审核不通过,一般是什么原因?
java·人工智能·算法·大模型备案·算法备案·大模型登记
秋天的怀念_David1 小时前
算法一千零一夜 · 第二十三夜 电力民生写成的曲线
java·程序人生·算法
吴名氏.1 小时前
Java转AI Agent教程(第五周)Prompt工程
java·人工智能·prompt·ai agent
8Qi81 小时前
DDD架构演进
java·分布式·mvc·ddd
paopaokaka_luck2 小时前
灾害应急物资管理系统(AI应急助手、Echarts可视化数据看板、捐赠入库联动、 物资全流程管理、库存变动追溯、灾情资讯与互动反馈、物资发放公示)
java·前端·javascript·spring boot·mysql·tomcat·echarts