5

I found a tuto to manage exceptions from this site. So here is my handler :

@Controller
@RequestMapping("/adminrole")
public class AdminRole {

    ...

    @ExceptionHandler({org.hibernate.exception.ConstraintViolationException.class})
    public ModelAndView handlePkDeletionException(Exception ex) {

        ModelAndView model = new ModelAndView("errorPage");

        model.addObject("message", "customised message with data to display in error page");

        return model;

    }

}

Now I want to pass some data , for example the column name of the primary key causing the exception , to the handler in order to display a customised message in the error page. So how to pass those data to the handler ?

pheromix
  • 18,213
  • 29
  • 88
  • 158

1 Answers1

8

To pass your own data to the @ExceptionHandler method, you need to catch the framework exceptions in the service layer, and throw your own custom exception by wrapping with the additional data.

Service layer:

public class MyAdminRoleService {
    public X insert(AdminRole adminRole) {
         try {
            //code
         } catch(ConstraintViolationException exe) {
            //set customdata from exception
            throw new BusinessException(customdata);
         }
    }
}

Controller layer:

@Controller
@RequestMapping("/adminrole")
public class AdminRole {

    @ExceptionHandler({com.myproject.BusinessException.class})
        public ModelAndView handlePkDeletionException(BusinessException ex) {
            String errorMessage  = ex.getErrorMessage(); 
            ModelAndView model = new ModelAndView("errorPage");

            model.addObject("message", errorMessage);

            return model;

        }
    }

P.S.: I have taken ConstraintViolationException only as an example, but you can apply the same concept for any framework exceptions for which you wanted to add an additional data.

Vasu
  • 21,832
  • 11
  • 51
  • 67