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

Spring Boot中无法自定义HttpMediaTypeNotAcceptableException的@ExceptionHandler

解决Spring HttpMediaTypeNotAcceptableException异常处理冲突问题

你遇到的问题根源是:自定义异常处理器继承了ResponseEntityExceptionHandler,而这个父类中既有专门处理HttpMediaTypeNotAcceptableException的方法,还有一个泛型处理Exception的方法,导致Spring无法确定使用哪个实现,从而抛出匹配歧义错误。

直接重写父类中专门处理该异常的方法即可解决问题:

@RestControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // 构建自定义错误响应体
        Map<String, Object> errorBody = new HashMap<>();
        errorBody.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        errorBody.put("status", status.value());
        errorBody.put("error", "媒体类型不支持");
        errorBody.put("message", "当前接口仅接受application/json格式响应,请调整请求头Accept参数");
        errorBody.put("path", request.getDescription(false).replace("uri=", ""));

        // 返回自定义响应,保持原状态码,也可按需修改
        return new ResponseEntity<>(errorBody, headers, status);
    }
}

原理说明

  • ResponseEntityExceptionHandler本身就提供了handleMediaTypeNotAcceptable方法处理该异常,通过重写这个方法,Spring会优先使用子类的实现,避免和父类的泛型handleException方法产生匹配歧义。
  • 这种方式无需在每个控制器的@GetMapping/@PostMapping中添加produces参数,当请求头Accept指定不支持的类型(比如application/xml)时,会自动进入重写的方法,返回你自定义的错误内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:13:08