@ResponseStatus,客户端没有收到错误消息

时间:2017-04-06 19:13:19

标签: java rest spring-mvc response

我的代码有自定义异常:

@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());
}

问题是客户端只收到错误代码但没有收到statusText "登录正忙" ,已经尝试添加一个捕获此异常的方法

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

但是,消息在某处丢失,客户得到了这样的回复:

1 个答案:

答案 0 :(得分:0)

您的@ResponseBody方法错过了handleException,而使用您当前的代码返回void ,即您没有通过{{1} } body,如下图所示:

response

或者您使用@ResponseBody @ExceptionHandler(LoginIsBusyException.class) public String handleException(HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy"); } 生成标题和正文,如下所示

ResponseEntity