Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data to an exceptionhandler?

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 ?

like image 747
pheromix Avatar asked Feb 05 '23 19:02

pheromix


1 Answers

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.

like image 117
developer Avatar answered Feb 15 '23 07:02

developer