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

Spring Boot中如何通过Pattern匹配优化枚举类型验证错误信息

解决方案:提取自定义枚举异常信息

问题的核心是Jackson抛出的HttpMessageNotReadableException是外层包装异常,你的自定义错误消息被包含在它的嵌套异常(你在枚举fromValues中抛出的IllegalArgumentException)里。我们只需要从异常链中提取这个自定义消息即可。

修改你的异常处理器,添加异常链遍历逻辑,直接获取自定义错误信息:

package com.example.enumhandler.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;

@RestControllerAdvice
public class UserExceptionHandler{

    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    public ResponseEntity<?> handleHttpMessageNotReadableException(
            HttpMessageNotReadableException ex,
            HttpServletRequest request
    ){
        HttpStatus badRequest = HttpStatus.BAD_REQUEST;
        // 提取自定义错误消息
        String errorMessage = extractCustomEnumErrorMessage(ex);

        ErrorResponse error = ErrorResponse
                .builder()
                .timestamp(LocalDateTime.now())
                .status(badRequest.getReasonPhrase())
                .code(badRequest.value())
                .message(errorMessage)
                .build();

        return new ResponseEntity<>(error, badRequest);
    }

    /**
     * 遍历异常链,找到我们自定义抛出的IllegalArgumentException并返回其消息
     */
    private String extractCustomEnumErrorMessage(Throwable ex) {
        Throwable currentException = ex;
        while (currentException != null) {
            if (currentException instanceof IllegalArgumentException) {
                return currentException.getMessage();
            }
            currentException = currentException.getCause();
        }
        // 如果未找到自定义异常,返回原始消息作为 fallback
        return ex.getLocalizedMessage();
    }
}

方案优势

  • 不依赖字符串截取:避免因Jackson版本更新导致消息格式变化而失效
  • 逻辑清晰可靠:直接从异常链中获取自定义错误信息,符合异常设计的初衷
  • 版本兼容性强:兼容所有Java版本,无需依赖特定API
  • 容错机制完善:保留fallback逻辑,确保未找到自定义异常时仍能返回合理错误信息

内容的提问来源于stack exchange,提问作者Gianni Spear

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:30:29