Spring @ExceptionHandler and RedirectAttributes

Since Spring 4.3.5 and 5.0 M4, it supports RedirectAttributes argument in the @ExceptionHandler method.


	@ExceptionHandler(MyCustomException.class)
	public String handleError1(MyCustomException e, RedirectAttributes redirectAttributes) {
	
		redirectAttributes.addFlashAttribute("message", "abcdefg");
		return "redirect:/viewName";
		
	}

	@ExceptionHandler(MultipartException.class)
	public String handleError2(MultipartException e, RedirectAttributes redirectAttributes) {

		redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
		return "redirect:/viewName";

	}

P.S Read this SPR-14651

Noted
If you are using Spring < 4.3.5, do not add this RedirectAttributes as the argument into the @ExceptionHandler method, otherwise, Spring will not able to catch the thrown exception.

References

  1. SPR-14651
  2. Spring @ExceptionHandler

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments