@ResponseStatus,客户端没有收到错误信息
@ResponseStatus, the client does not receive an error message
我有自定义异常的代码:
@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());
}
问题是客户端只收到error code,没有收到statusText"Login is busy",已经尝试添加捕获这个异常的方法
@ExceptionHandler(LoginIsBusyException.class)
public void handleException(HttpServletResponse response) throws IOException
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy");
}
但是,消息在某处丢失了,客户收到了这样的回复:
您的 handleException
方法错过了 @ResponseBody
,并且 returns void
使用您当前的代码,即,您没有通过 response
body,如下所示:
@ResponseBody
@ExceptionHandler(LoginIsBusyException.class)
public String handleException(HttpServletResponse response) throws IOException
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy");
}
否则您使用 ResponseEntity
生成 header 和 body,如下所示
@ExceptionHandler(LoginIsBusyException.class)
public ResponseEntity<String>
handleException(LoginIsBusyException exe) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Login is busy");
}
我有自定义异常的代码:
@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());
}
问题是客户端只收到error code,没有收到statusText"Login is busy",已经尝试添加捕获这个异常的方法
@ExceptionHandler(LoginIsBusyException.class)
public void handleException(HttpServletResponse response) throws IOException
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy");
}
但是,消息在某处丢失了,客户收到了这样的回复:
您的 handleException
方法错过了 @ResponseBody
,并且 returns void
使用您当前的代码,即,您没有通过 response
body,如下所示:
@ResponseBody
@ExceptionHandler(LoginIsBusyException.class)
public String handleException(HttpServletResponse response) throws IOException
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy");
}
否则您使用 ResponseEntity
生成 header 和 body,如下所示
@ExceptionHandler(LoginIsBusyException.class)
public ResponseEntity<String>
handleException(LoginIsBusyException exe) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Login is busy");
}