扩展ResponseEntityExceptionHandler有什么用?

what is the usage of extending ResponseEntityExceptionHandler?

谁能解释一下扩展 ResponseEntityExceptionHandler 的用途是什么。如果我不扩展 ResponseEntityExceptionHandler GlobalExceptionHandler 正在工作并向客户端发送响应。

@ControllerAdvice
public class GlobalExceptionHandler  extends ResponseEntityExceptionHandler{
    @ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
    public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();

        if (ex instanceof UserNotFoundException) {
            HttpStatus status = HttpStatus.NOT_FOUND;
            UserNotFoundException unfe = (UserNotFoundException) ex;

            return handleUserNotFoundException(unfe, headers, status, request);
        } else if (ex instanceof ContentNotAllowedException) {
            HttpStatus status = HttpStatus.BAD_REQUEST;
            ContentNotAllowedException cnae = (ContentNotAllowedException) ex;

            return handleContentNotAllowedException(cnae, headers, status, request);
        } else {
            HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
            return handleExceptionInternal(ex, null, headers, status, request);
        }
    }

}

@ControllerAdvice
public class GlobalExceptionHandler{
    @ExceptionHandler({ UserNotFoundException.class, ContentNotAllowedException.class })
    public final ResponseEntity<ApiError> handleException(Exception ex, WebRequest request) {
        HttpHeaders headers = new HttpHeaders();

        if (ex instanceof UserNotFoundException) {
            HttpStatus status = HttpStatus.NOT_FOUND;
            UserNotFoundException unfe = (UserNotFoundException) ex;

            return handleUserNotFoundException(unfe, headers, status, request);
        } else if (ex instanceof ContentNotAllowedException) {
            HttpStatus status = HttpStatus.BAD_REQUEST;
            ContentNotAllowedException cnae = (ContentNotAllowedException) ex;

            return handleContentNotAllowedException(cnae, headers, status, request);
        } else {
            HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
            return handleExceptionInternal(ex, null, headers, status, request);
        }
    }

}

ResponseEntityExceptionHandler 用于通常对 Spring 的默认异常处理程序感到满意的情况 - 除了少数,然后可能会被覆盖。

查看 API 文档中所有受保护的方法:ResponseEntityExceptionHandler

您的 GlobalExceptionHandler 已经在接受任何异常并自定义处理两个特定的异常。

如果您坚持使用 ResponseEntityExceptionHandler,可以通过扩展 class 并实现 handleExceptionInternal():

来实现类似的效果
@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    public handleExceptionInternal() {
        ...
    }
}