java - 异常处理程序无法处理 `spring-boot-starter-data-rest`

标签 java spring rest spring-mvc kotlin

我上次体验 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 时,我无法添加异常处理程序。

我尝试过的:

  • 我尝试在 Controller 上注册异常处理程序方法。
  • 我尝试创建用 @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 对象的异常处理程序的正确方法是什么。

最佳答案

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

@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 答案(我已经丢失了)。在该答案中,答案建议在处理程序中包含 @EnableWebMVC 。我发现这对我来说没有必要”

关于java - 异常处理程序无法处理 `spring-boot-starter-data-rest`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33327499/

相关文章:

Java EE/GlassFish - 线程和连接

java 示例使 JLabel 文本发光或 NEON

spring - 在 Spring Rest 中使用 JSON 的 HTTP POST

json - 将包含动态键的 REST API 返回的 JSON 映射到 Golang 中的结构

mongodb - 在 Grails REST API 中自动将蛇案例转换为 Camel 案例?

java - 如何读取lucene 5.5.5索引?

java - 数据库驱动程序需要支持分布式事务还是数据库本身需要支持?

java - Spring 网络流程 : setting request parameter for JUnit test

java - Spring 框架是否因 Jackson 依赖而容易受到攻击

php - Paypal SDK错误 "Credential not found for default user"