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

Spring Boot 3.0.2中ResponseEntityExceptionHandler重写方法报错咨询

Spring Boot 3.0.2中ResponseEntityExceptionHandler的handleExceptionInternal方法覆盖问题解决

问题原因

Spring Boot 3基于Spring Framework 6,ResponseEntityExceptionHandler类中的handleExceptionInternal方法签名发生了关键变更:

  • 旧版(Spring Boot 2.x)的状态码参数类型为HttpStatus
  • 新版(Spring Boot 3.x)替换为更通用的HttpStatusCode(HttpStatus是它的实现类)

你的旧代码方法签名与父类当前定义不匹配,因此@Override注解会触发“未覆盖父类方法”的错误。

最优解决方案

修改handleExceptionInternal的方法签名,匹配父类的新定义即可,示例代码如下:

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

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(
            Exception ex,
            @Nullable Object body,
            HttpHeaders headers,
            HttpStatusCode statusCode,
            WebRequest request) {
        // 自定义异常处理逻辑,比如统一包装错误响应
        if (body == null) {
            body = new CustomErrorResponse(statusCode.value(), ex.getMessage());
        }
        return super.handleExceptionInternal(ex, body, headers, statusCode, request);
    }

    // 自定义异常处理示例
    @ExceptionHandler(CustomBusinessException.class)
    public ResponseEntity<CustomErrorResponse> handleCustomBusinessException(CustomBusinessException ex) {
        CustomErrorResponse response = new CustomErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

// 自定义错误响应体示例
class CustomErrorResponse {
    private int status;
    private String message;

    public CustomErrorResponse(int status, String message) {
        this.status = status;
        this.message = message;
    }

    // getter/setter 省略
}

其他方案对比

  • 不继承ResponseEntityExceptionHandler:直接用@RestControllerAdvice+@ExceptionHandler处理所有异常,灵活性更高,但需要自行处理Spring内置的所有异常(如参数校验、请求方式不匹配等),不如继承父类省心。
  • 使用ProblemDetails规范:Spring 6支持RFC 7807标准的ProblemDetails,可让异常类实现ProblemDetail或在处理时返回该对象,更符合REST API错误响应规范,示例:
@ExceptionHandler(CustomBusinessException.class)
public ProblemDetail handleCustomBusinessException(CustomBusinessException ex) {
    ProblemDetail problemDetail = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
    problemDetail.setTitle("业务异常");
    problemDetail.setDetail(ex.getMessage());
    problemDetail.setProperty("errorCode", ex.getErrorCode());
    return problemDetail;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:15