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

Spring Boot中MethodArgumentTypeMismatchException错误消息自定义转义方案

解决方案

方案1:全局Jackson序列化配置(最简单,无代码侵入)

直接在项目的application.properties中添加一行配置即可:

spring.jackson.generator.escape-html = true

该配置会开启Jackson序列化的HTML字符转义特性,所有JSON返回值中的<、>、&、'、"等HTML敏感字符会自动被转义为对应的Unicode编码(如<转义为\u003c,>转义为\u003e),覆盖所有接口响应包括异常返回的message字段,完全不需要修改原有业务代码,也不影响你保留Integer类型的参数定义。

如果你使用application.yml,配置格式如下:

spring:
  jackson:
    generator:
      escape-html: true

方案2:自定义全局异常处理(仅针对异常消息转义)

如果你不需要全局转义所有接口返回,只想针对MethodArgumentTypeMismatchException的报错消息做处理,可重写ResponseEntityExceptionHandler的对应方法,之前处理失效大概率是没有重写对对应方法:

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleTypeMismatch(
            org.springframework.beans.TypeMismatchException ex,
            HttpHeaders headers,
            HttpStatusCode status,
            WebRequest request
    ) {
        String rawMessage = ex.getMessage();
        // 自定义转义规则
        String escapedMessage = rawMessage.replace("<", "\\u003c")
                .replace(">", "\\u003e")
                .replace("&", "\\u0026");
        // 构造符合你项目格式的响应体
        Map<String, Object> responseBody = Map.of(
                "code", status.value(),
                "message", escapedMessage
        );
        return handleExceptionInternal(ex, responseBody, headers, status, request);
    }
}

内容的提问来源于stack exchange,提问作者peter.petrov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:30:03