2015-10-25 52 views
1

我最後的Java/Spring體驗大約在四年前。我已經開始用Kotlin學習Spring Boot了。異常處理程序不能使用`spring-boot-starter-data-rest`

我創建了一個RESTful Web服務(在科特林)這樣的,它工作正常:

@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

在這兩種情況下,標註的交叉例外顧問類,除了不被映射,而是我得到:

白色標籤錯誤頁面

這應用程序沒有明確的映射/錯誤,所以你將這看作是後備。

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

問:

什麼是春天引導正確的方法來註冊一個異常處理程序,可以返回序列化ErrorResponse對象。

回答

0

我能得到它的工作通過註冊以下異常處理程序:

@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。我發現這在我的情況下不是必需的「