Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments