Custom Exception Messages Using the Spring Frame

I use spring and Hibernate in my application. There is one scenario in which I insert the same records more than once, so the application correctly throws a Constraint exception because I applied a unique constraint in one of the db columns ..

But I have to display some kind of custom message such as “record already exists” instead of showing a Hibernate exception.

How can I with spring framework.

Any hints or examples that have been greatly appreciated.

Hi,

Raju

+6
source share
3 answers

Yes, you can exclude from the controller:

@ExceptionHandler(Exception.class) public ModelAndView handleMyException(Exception exception) { ModelAndView mv = new ModelAndView("error"); mv.addObject("message"."record already exists"); return mv; } 

Because of what you can catch any tpe exception, just insert it as parameter in @ExceptionHandler

Hope this helps.

+6
source

I ran into the same problem, but in my case you can duplicate one or more fields (username or email address). Therefore, org.hibernate.exception.ConstraintViolationException is not specific enough to say whether a username or letter was caused by this exception and which message was displayed last.

I just looked at danny.lesnik’s answer , but it’s not great, as it just redirects to the “highlighted” page. Assuming you were simply redirecting the user of the page, he would avoid creating a new page that you would say. However, I suppose you already have a Spring validator doing some form validation work. Therefore, in my case, I decided to simply perform duplicate field checks (username and email address) in one place (in the validator). It seems like a more appropriate, consistent (located with the rest of the check) and cleaner solution.

Here is some code to illustrate:

My controller

 @Controller public class WebController { @Autowired private UserServiceImpl userService; @Autowired private CustomUserDetailsValidator customUserDetailsValidator; ... @RequestMapping(value = "/login/create-account", method = RequestMethod.POST) public String createAccount(@ModelAttribute("user") CustomUserDetails user, BindingResult result, Model model, SessionStatus status) { customUserDetailsValidator.validate(user, result); if(result.hasErrors()){ model.addAttribute("user", user); // Print the errors to the console - FIXME: log error instead System.out.println("Validation errors:"); for (FieldError error : result.getFieldErrors()) { System.out.println(error.getField() + " - " + error.getDefaultMessage()); } return "login/create-account"; } else{ userService.registerUser(user); return "redirect:/login/create-account-success"; } } ... } 

My validator

 public class CustomUserDetailsValidator implements Validator { @Autowired private UserServiceImpl userService; ... @Override public void validate(Object target, Errors errors) { // some simple validations // and here some complex validation (is username or email used duplicated?) if(errors.getAllErrors().size() == 0){ if ( userService.doesUsernameAlreadyExist( user.getUsername() ) ) errors.rejectValue(usernameFieldName, "duplicate.username","username already exists"); if ( userService.doesEmailAlreadyExist( user.getEmail() ) ) errors.rejectValue(emailFieldName, "duplicate.email","email already exists"); } } } 

I'm not sure if this is the best way to do this, but I thought that my solution would increase the extension (you can add various checks for any other restriction).

Hope this helps others, and it would also be interesting to know more about this developer.

+2
source

you can catch the exception thrown using spring / hibernate and throw one of your own exceptions that will contain the message “already exists”, you can even find a localized message from the resource bundle and map this message to your presentation level (for example, jsp )

0
source

Source: https://habr.com/ru/post/896053/


All Articles