spring 当异常扩展到ResponseStatusException时,如何在控制器建议中记录异常?

y0u0uwnf  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(136)

我无法在控制器建议中捕获异常并记录这些异常。这些异常被扩展到ResponseStatusException。我尝试了这个方法,但没有成功。

@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

@Override
protected ResponseEntity<Object> handleExceptionInternal(
        @NonNull Exception ex,
        @Nullable Object body,
        @NonNull HttpHeaders headers,
        HttpStatus status,
        @NonNull WebRequest request) {
    if (status.is5xxServerError()) {
        LOGGER.error("An exception occurred, which will cause a {} response", status, ex);
    } else if (status.is4xxClientError()) {
        LOGGER.warn("An exception occured, which will cause a {} response", status, ex);
    } else {
        LOGGER.debug("An exception occured, which will cause a {} response", status, ex);
    }
    return super.handleExceptionInternal(ex, body, headers, status, request);
}
}

我怎样才能达到这个要求呢?

nr7wwzry

nr7wwzry1#

我建议不要将从ResponseEntityExceptionHandler扩展作为第一个测试。
通过执行类似以下操作来创建异常处理程序:

@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<Object> testHandler(Exception ex, WebRequest request) {
    return new ResponseEntity<>("whatever", HttpStatus.NOT_FOUND);
}

我怀疑您没有告诉Spring通过以下方式处理此特定异常:

@ExceptionHandler(ResponseStatusException.class)

相关问题