I have code with a custom exception:
@ResponseStatus(value = BAD_REQUEST, reason = "Login is busy")
public class LoginIsBusyException extends RuntimeException{
}
And a method that can throw it:
@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());
}
The problem is that the client receives only the error code but does not receive the statusText "Login is busy", Already tried to add a method catching this exception
@ExceptionHandler(LoginIsBusyException.class)
public void handleException(HttpServletResponse response) throws IOException
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy");
}
But, the message is lost somewhere and the customer gets this response:
You have missed @ResponseBody
for your handleException
method and also it returns void
with your current code i.e., you are NOT passing the response
body, as shown below:
@ResponseBody
@ExceptionHandler(LoginIsBusyException.class)
public String handleException(HttpServletResponse response) throws IOException
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Login is busy");
}
or else you use ResponseEntity
to produce both header and body as shown below
@ExceptionHandler(LoginIsBusyException.class)
public ResponseEntity<String>
handleException(LoginIsBusyException exe) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Login is busy");
}