0

我正在尝试在我的 Spring Boot 应用程序中为所有类型的 RestClientResponseException 创建自己的自定义响应

控制器类抛出的自定义异常:

throw new HealthCheckRestException(ex.getResponseBodyAsString());

我的 ExceptionHandler 类是这样的:

@Order(Ordered.HIGHEST_PRECEDENCE)
@EnableWebMvc
@ControllerAdvice
public class AvailExceptionHandler {

private static final Logger logger = Logger.getLogger(AvailExceptionHandler.class);

@ExceptionHandler(value=HealthCheckRestException.class)
    public AvailResponse handleHttpErrorResponse(final HealthCheckRestException ex, final HttpServletRequest request){
        logger.error("RestClientException is thrown from HealthCheck API: with status :"
                + ex.getStatusText() + " and exception : "+ ex.getMessage());
        return new AvailResponse(AvailStatus.ERROR);
    }
}

我已经尝试了所有可能的情况,例如:

1) Trying @ExceptionHandler inside the controller class
2) Including @ControllerAdvice(basePackages = "com.org.availabillity.utilities") to scan for specific packages where the controller is defined.
3) Using @Order(Ordered.HIGHEST_PRECEDENCE) to set precedence
4) Using @RestControllerAdvice

抛出异常并调用带有@ExceptionHandler注解的方法后似乎没有任何拦截

现在卡住了一段时间,需要一些帮助。非常感谢您对此的帮助。

I am using spring-web-5.0.6.RELEASE
4

2 回答 2

0

尝试这样的事情:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Map;

@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public final class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
  private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

  private static final boolean INCLUDE_STACKTRACE = false;

  @ExceptionHandler(Exception.class)
  public ResponseEntity<Map<String, Object>> handle(final WebRequest request, final Throwable exception) {
    log.debug("Fallback handler executed for unhandled exception:", exception);
    return new ResponseEntity<>(new DefaultErrorAttributes().getErrorAttributes(request, INCLUDE_STACKTRACE),
        HttpStatus.INTERNAL_SERVER_ERROR);
  }

  // IllegalArgumentException is not "entirely correct", so replace this with your own
  @ExceptionHandler(IllegalArgumentException.class)
  public ResponseEntity<Map<String, Object>> handle1(final WebRequest request, final Throwable exception) {
    log.debug("Fallback handler executed for unhandled exception:", exception);
    return new ResponseEntity<>(new DefaultErrorAttributes().getErrorAttributes(request, INCLUDE_STACKTRACE),
        HttpStatus.INTERNAL_SERVER_ERROR);
  }

  // TODO: Keep adding exception(s) handlers for particular cases
}

GlobalExceptionHandler只是一个可以放置在任何地方的 Spring 组件/bean,前提是您配置了要发现的位置。

@EnableWebMvc应该放在一个用 . 注释的类中@Configuration。此外,如果您正在使用Spring Boot,则很可能不需要它,因为它会被推断出来。

于 2019-09-13T20:22:58.623 回答
0

这是我的 Handler 类的小例子;

@ControllerAdvice
public class GlobalExceptionHandler {

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

    if (ex instanceof QueryNotFoundException) {
        HttpStatus status = HttpStatus.NOT_FOUND;
        QueryNotFoundException qnfe = (QueryNotFoundException) ex;
        return handleQueryNotFoundException(qnfe, 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);
    }
于 2019-09-13T20:26:01.857 回答