简体   繁体   English

如何通过@ControllerAdvice中的@ResponseStatus捕获异常

[英]How to catch exceptions by @ResponseStatus in @ControllerAdvice

I'm looking for a way to handle communications with the front end in case of error driven by @ResponseStatus so that 我正在寻找一种方法来处理与前端的通信,以防由@ResponseStatus驱动错误,以便

  • if the response is a 400/401/403 I can log an info and send a specific message out 如果响应是400/401/403,我可以记录信息并发送特定的消息
  • if the response is a 500 I can log an error and send another specific message out 如果响应是500我可以记录错误并发送另一个特定的消息

and so on. 等等。

In our Api gateway we have a RextExceptionController ( @ControllerAdvice ) where we handle exceptions and return our own DTO to the front end. 在我们的Api网关中,我们有一个RextExceptionController@ControllerAdvice ),我们处理异常并将我们自己的DTO返回到前端。

Everything works fine if I target single exceptions (see example below) but obviously this doesn't work if I want to target just the response HTTP status. 如果我针对单个异常(参见下面的示例),一切正常,但是如果我想仅仅针对响应HTTP状态,这显然不起作用。

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex) {
    ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
    apiError.setMessage("Bla bla Status 400");
    return buildResponseEntity(apiError);
}

@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(
  HttpMediaTypeNotSupportedException ex,
  HttpHeaders headers,
  HttpStatus status,
  WebRequest request) {
    ApiError apiError = new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    apiError.setMessage("Bla bla Status 415");
    return buildResponseEntity(apiError);
}

This is not a sustainable way to handle it as future development from different teams (the application is based on a micro service architecture) may throw any sort of exceptions really and I don't want to run after all the possible exceptions but to base the handler on response status. 这不是一种可持续的方式来处理它,因为来自不同团队的未来开发(应用程序基于微服务架构)可能真的抛出任何类型的异常,我不想在所有可能的异常之后运行但是基于响应状态的处理程序。

Any tips/ideas? 任何提示/想法?

Cheers. 干杯。

你可以使用一个http处理程序拦截器来拦截请求完成后的http响应,并根据你所拥有的状态做一些动作,查看这篇文章https://www.baeldung.com/spring-mvc-handlerinterceptor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM