2017-04-06 65 views
1

我有代碼自定義異常:@ResponseStatus,客戶端沒有收到錯誤消息

@ResponseStatus(value = BAD_REQUEST, reason = "Login is busy") 
    public class LoginIsBusyException extends RuntimeException{ 
} 

而一個方法,可以把它:

@RequestMapping(method = POST) 
public void registration(@RequestBody UserRest user) throws 
LoginIsBusyException{ 
    userService.checkAlreadyExist(user.getLogin(), user.getMail()); 
    user.setActive(false); 
    UserRest userRest = userService.addUser(user); 
    Integer randomToken = randomTokenService.getRandomToken(userRest.getMail()); 
    mailService.sendMail(randomToken, userRest.getLogin(), userRest.getMail()); 
} 

的問題是,客戶端只接收錯誤代碼但未收到狀態文本「登錄很忙」,已嘗試添加捕獲此異常的方法

@ExceptionHandler(LoginIsBusyException.class) 
public void handleException(HttpServletResponse response) throws IOException 
{ 
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy"); 
} 

但是,該消息某處丟失,客戶得到這樣的迴應:

回答

0

你已經錯過了@ResponseBodyhandleException方法並且還回報void與當前的代碼,即,你是不是經過response體,如下圖所示:

@ResponseBody 
@ExceptionHandler(LoginIsBusyException.class) 
public String handleException(HttpServletResponse response) throws IOException 
{ 
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy"); 
} 

要不你用ResponseEntity同時生產標題和正文如下圖所示

@ExceptionHandler(LoginIsBusyException.class) 
public ResponseEntity<String> 
       handleException(LoginIsBusyException exe) { 
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Login is busy"); 
} 
+0

非常感謝您的回答。但是我沒有使用'@ ResponseBody',因爲我使用了'@ RestController'註解。我以不同的方式解決了這個問更確切地說,我錯了等待郵件在標題中。消息在json主體中。我在SoapUi得到迴應後明白了這一點。自定義異常正常工作,這是我的錯誤。你的回答也是正確的。 –

相關問題