我上次体验 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/