ExceptionHandler

User Define Exception

We need to define the exception that to be handle by our own. For instance, a product search page. When user key in a bad word to search, we’d like to show error page.

public class BadKeywordsException extends Exception {

	private static final long serialVersionUID = 1L;

	public BadKeywordsException(String keyword) {
		super("Please try other keywords instead of " + keyword);
	}
}

Controller

@Controller
public class SearchController {

   @Autowired
   private SearchService service;
   
   @RequestMapping("/search")
   public String search(String keyword, Model model) throws Exception {
        DBResult result = service.findByKeyword(keyword);       
 
	if ("fuck".equals(keyword)) {
		throw new BadKeywordsException(keyword);
	} 
	if (result == null) {
		throw new Exception(keyword);
	}
	model.addAttribute("keyword", keyword);
        model.addAttribute("result", result);
	return "result"; 
    }
  

    // code omitted
}

Class Level @ExceptionHandler

Annotation @ExceptionHandler take class as argument. If empty, will default to any exception listed in the method argument list.

@ExceptionHandler(BadKeywordsException.class)
public ModelAndView handleException(BadKeywordsException e) {
    ModelAndView modelAndView = new ModelAndView("keyword-error"); 
    modelAndView.addObject("errorMessage", e.getMessage()); 
    return modelAndView;
}

Global @ExceptionHandler

Global exception handler can be done with annotated @ControllerAdvice and define a method annotated with @ExceptionHandler just like the example above. This snippet code show that @ExceptionHandler take 1 argument, which is Exception.class and no method argument. Whenever any exception encounter with it will show to global-error.jsp

@ControllerAdvice
public class ApplicationExcepionHandler
{
     @ExceptionHandler(Exception.class)
     public ModelAndView handleException() {
         return new ModelAndView("global-error");
     }

}

 

ExceptionHandler

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.