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

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐