有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在寻找一种方法来处理由@ResponseStatus驱动的错误情况下与前端的通信,以便

  • 如果响应是400/401/403,我可以记录信息并发送特定消息
  • 如果响应为500,我可以记录一个错误并发送另一条特定消息

等等

在我们的Api网关中,我们有一个RextExceptionController@ControllerAdvice),在这里我们处理异常并将自己的DTO返回到前端

如果我只针对单个异常(参见下面的示例),那么一切都可以正常工作,但是如果我只针对响应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);
}

这不是一种可持续的处理方法,因为来自不同团队的未来开发(应用程序基于微服务体系结构)可能会引发任何类型的异常,我不想在所有可能的异常之后运行,而是基于响应状态来运行处理程序

有什么建议/想法吗

干杯


共 (1) 个答案