You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JHipster v6.6.0自定义错误消息展示:替代CustomParameterizedException方案

JHipster v6.6.0 中 CustomParameterizedException 的替代方案

嘿,刚好对JHipster这个版本的异常处理调整有点了解,来给你解答下:

首先明确说:CustomParameterizedException确实已经在JHipster v6.x的更新中被移除了,到v6.6.0时它已经不是框架默认提供的类了。不过不用担心,官方提供了更统一的替代方案,还有自定义的思路:

1. 使用内置的 ParameterizedException 类

这是官方用来替代旧CustomParameterizedException的类,功能完全覆盖,支持参数化的国际化错误消息。使用方式很简单:

代码示例

// 抛出异常时传入消息键和参数
throw new ParameterizedException("error.user.invalid", username, email);

配置国际化消息

在src/main/resources/i18n/messages.properties(对应其他语言的文件比如messages_zh_CN.properties)里添加对应的消息键:

error.user.invalid=用户 {0} 的邮箱 {1} 格式无效,请检查后重试

框架的异常处理机制会自动读取这个配置,替换参数后返回给前端。

2. 自定义符合需求的异常类

如果内置的ParameterizedException满足不了你的特殊需求,也可以自己创建一个异常类,只要实现JHipster的I18nMessageException接口,就能和框架的异常处理流程兼容:

自定义异常类示例

import org.springframework.http.HttpStatus;
import tech.jhipster.web.util.I18nMessageException;

public class CustomBusinessException extends RuntimeException implements I18nMessageException {
    private final String messageKey;
    private final Object[] parameters;
    private final HttpStatus httpStatus;

    // 构造方法可以根据需求调整参数
    public CustomBusinessException(String messageKey, HttpStatus httpStatus, Object... parameters) {
        super(messageKey);
        this.messageKey = messageKey;
        this.parameters = parameters;
        this.httpStatus = httpStatus;
    }

    @Override
    public String getMessageKey() {
        return messageKey;
    }

    @Override
    public Object[] getParameters() {
        return parameters;
    }

    // 可以额外添加获取Http状态码的方法,方便统一处理状态
    public HttpStatus getHttpStatus() {
        return httpStatus;
    }
}

使用自定义异常

throw new CustomBusinessException("error.order.outOfStock", HttpStatus.BAD_REQUEST, productName);

同样在消息文件里配置对应的键即可。

这个调整是JHipster在v6.x中为了统一异常体系做出的改动,移除了旧的自定义异常类,换成了更通用的实现,同时保留了自定义扩展的灵活性。

内容的提问来源于stack exchange,提问作者Orn Arnar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:03:13