【问题标题】:Exception Handler Not Working with `spring-boot-starter-data-rest`异常处理程序不适用于`spring-boot-starter-data-rest`
【发布时间】:2015-10-25 08:04:38
【问题描述】:

我上一次使用 Java/Spring 是在大约四年前。我已经开始使用 Kotlin 学习 Spring Boot。

我已经创建了一个像这样的 RESTful Web 服务(在 Kotlin 中),它运行良好:

@RequestMapping("/authorization")
public fun authorization(@RequestParam(value = "network-type", defaultValue = "Facebook") name: String,
                         @RequestParam(value = "oauth-token") oauthToken: String,
                         @RequestParam(value = "oauth-token-secret",
                                 required = false) oauthTokenSecret: String?): Authorization
{
    //TODO: Handle other social network types
    return facebookAuth.authorization(oauthToken)
}

现在我无法为 facebookAuth 抛出 UnauthorizedException 添加异常处理程序。

我的尝试:

  • 我尝试在控制器上注册异常处理方法。
  • 我尝试过创建带有@ControllerAdvice 注释的横切异常顾问类

在这两种情况下,异常都没有被映射,而是我得到:

白标错误页面

此应用程序没有显式映射 /error,因此您将其视为后备。

Sun Oct 25 16:00:43 PHT 2015
There was an unexpected error (type=Internal Server Error, status=500).
Invalid OAuth access token.

问题:

使用 Spring Boot 注册可以返回序列化 ErrorResponse 对象的异常处理程序的正确方法是什么。

【问题讨论】:

    标签: java spring rest spring-mvc kotlin


    【解决方案1】:

    我能够通过注册以下异常处理程序使其工作:

    @ControllerAdvice
    public class ExceptionHandler : ResponseEntityExceptionHandler()
    {
    
        @ExceptionHandler(Throwable::class)
        @ResponseBody
        internal fun onException(ex: Throwable): ErrorResponse
        {
            //TODO: Replace instanceof with polymorphism
            var responseCode = ResponseCode.VAMPServiceError
            if (ex is UnauthorizedException) {
                responseCode = ResponseCode.VAMPUnauthorized
            }
    
            val errorResponse = ErrorResponse(
                response = ResponseHeader(responseCode, ex.message))
            return errorResponse
        }
    }
    

    这是基于另一个 StackOverflow anwer(我已经丢失了)。在该答案中,建议在处理程序中包含@EnableWebMVC。我发现在我的情况下这不是必需的”

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2022-01-12
      • 2016-06-04
      • 1970-01-01
      • 2015-06-28
      • 2021-09-17
      • 2023-03-04
      • 2017-11-28
      相关资源
      最近更新 更多