java - Spring Boot @ControllerAdvice 异常处理程序未触发

标签 java spring spring-mvc spring-boot kotlin

我设置了以下 Controller 建议,以针对错误条件返回 API 契约(Contract):

@ControllerAdvice
public class ExceptionHandler : ResponseEntityExceptionHandler()
{
    @ExceptionHandler(Throwable::class)
    @ResponseBody
    public fun onException(ex: Throwable): ResponseEntity<ErrorResponse>
    {
        val errorResponse = ErrorResponse(
           response = ResponseHeader(ex.responseCode(), ex.message))
        return ResponseEntity(errorResponse, HttpStatus.UNAUTHORIZED);
    }

}

工作正常,然后停止工作。现在所有异常都被路由到 BasicErrorController,它返回以下格式:

{
  "timestamp" : 1450495303166,
  "status" : 403,
  "error" : "Forbidden",
  "message" : "Access Denied",
  "path" : "/profile/candidates"
}

上面是一个很好的固执己见的起点,但现在它不会妨碍你。

  • 我尝试用 ExceptionHandlerExceptionResolver 的一个实例替换错误处理程序,但没有奏效。
  • 我尝试过制作自己的 CustomErrorHandler,但这也不合适,因为在 HttpServletRequest 重新路由到自定义错误 Controller 时,原始异常已不再存在。需要此信息才能向客户端返回适当的响应。

我该怎么做:

  • 使 SpringBoot 将异常转发到异常 Controller 。
  • 恢复@ControllerAdvice 异常处理程序,这样我就可以返回适当的响应正文和状态代码。

关于启动 spring 日志:

main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in exceptionHandler
main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in responseEntityExceptionHandler

编辑:

在阅读了 Spring Boot 文档之后,我现在明白 BasicErrorController 应该只针对 没有@ControllerAdvice 处理的任何异常触发。这似乎没有发生。那么问题是为什么?

最佳答案

I also have a Spring Security filter that evaluates API-Key and Access-Token header credentials. @ControllerAdvice doesn't work here - fair enough, given we're not dealing with a controller endpoint!

使用 EntryPoint 和 AcessDeniedHandler 处理来自安全过滤器的异常。里面有可以配置的:

.exceptionHandling()

如果您在过滤器中扩展 AbstractAuthenticationProcessingFilter,则配置 FailureHandler。

 setAuthenticationFailureHandler()

如果您将应用程序部署在应用服务器下,Afaik ErrorController 将被覆盖。

关于java - Spring Boot @ControllerAdvice 异常处理程序未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366964/

相关文章:

java - 以编程方式允许@RequestMapping

java - Thawte证书查询

java - Spring RestTemplate 连接重置

java - 在测试中禁用 @Bean 的 initMethod

java - Spring MVC 3 异常 : An Errors/BindingResult argument is expected

unit-testing - 如何测试 spring 2.5 Controller 上使用的绑定(bind)器/属性编辑器

java - Hibernate 或 Java 中是否有类似于 PHP $_SESSION 的 Session 变量

java - Angular 6 和 spring boot 通过基于 session 的登录记住我

java - 如何返回多个字符串?

spring - 调用 spring 授权服务器 OAuth2 REST 端点