【问题标题】:override common spring exception handler覆盖常见的spring异常处理程序
【发布时间】:2020-09-28 15:58:53
【问题描述】:

我正在做一个项目,该项目实现了一个像这样的通用异常处理程序:

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(final Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

现在我想使用不受此异常处理影响的休息模板,但无论我尝试什么,所有异常都由公共处理程序处理。 知道如何使用带有覆盖上述错误处理程序的自定义错误处理程序的休息模板吗?

无法修改通用异常处理程序,所以我必须想办法解决它。

【问题讨论】:

  • 在您的@RestControllerAdvice 中使用@ExceptionHandler(Exception.class) 可作为引发所有 异常的包罗万象。我想您要么必须在建议中处理更具体的异常,要么根本不使用@RestControllerAdvice
  • “我想使用不受此异常处理影响的休息模板”是什么意思? RestTemplate 完全不受这些建议的影响。您的意思是使用RestTemplate 引起的异常最终会由该建议处理吗?

标签: spring spring-boot resttemplate


【解决方案1】:

我建议两种解决方案:

  • 您要么抛出您的@RestControllerAdvice 未处理的特定/新异常,这可能会导致重复异常
  • 或者,在您的休息调用级别本地捕获异常:
try {
    return restTemplate.postForObject("http://your.url.here", "YourRequestObjectForPostBodyHere", YourResponse.class);

} catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {

    if (HttpStatus.NOT_FOUND.equals(httpClientOrServerExc.getStatusCode())) {
        // your handling of "NOT FOUND" here  
        // e.g. throw new RuntimeException("Your Error Message here", httpClientOrServerExc);
    } else {
        // your handling of other errors here
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2018-12-15
    相关资源
    最近更新 更多