0

I am wondering how to bind exception handling method to url mapping method:

@Controller
public class UserController {

    @Autowired
    UserDao userDao;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String users(@ModelAttribute("model") ModelMap model) {
        model.addAttribute("userList", userDao.getAll());
        String[] b = new String[0];
        String a = b[1];
        return "user";
    }

    @ExceptionHandler(Exception.class)
    public String handleAllException(Exception ex, @ModelAttribute("model") ModelMap model) {
        model.addAttribute("error", "Exception happened");
        return "error_screen";
    }
}

I intentionally provoke java.lang.ArrayIndexOutOfBoundsException in users method. But I see that handleAllException method wasn't executed.

Question: What have I forgotten to get done to make Exception Handling work appropriately?

2
  • 1
    I think that you try to use annotation @ModelAttribute incorrectly. Please try something like that: ` @ExceptionHandler(Exception.class) public ModelAndView handleError(Exception exception) { //Code here return new ModelAndView("error"); }` Commented Jul 18, 2016 at 10:05
  • Thank you, @NguaCon! This is correct and helpful. Commented Jul 18, 2016 at 10:12

3 Answers 3

1

Try to do somedthing like this:

 @ExceptionHandler(Exception.class)
 public ModelAndView handleAllException(Exception ex) {
  ModelAndView model = new ModelAndView("error_screen");
  model.addAttribute("error", "Exception happened");
  return model;
 }
Sign up to request clarification or add additional context in comments.

Comments

0

Try the following

@ExceptionHandler(Exception.class) -> @ExceptionHandler({Exception.class})

1 Comment

This array declaration is not necessary, its needed only when we have more that one exception class
0

The reason is it has failed with the below exception while trying to invoke the handleAllException() method:

DEBUG [http-nio-8080-exec-6] --- ExceptionHandlerExceptionResolver: Failed to invoke @ExceptionHandler method: public java.lang.String controllers.handleAllException(java.lang.Exception,org.springframework.ui.ModelMap) java.lang.IllegalStateException: No suitable resolver for argument [1] [type=org.springframework.ui.ModelMap] HandlerMethod details:

Change the Method as below:

@ExceptionHandler(Exception.class)
    public String handleAllException(Exception ex) {
        // model.addAttribute("error", String.format("Exception happened"));
        return "error_screen";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.