Rudziankoŭ
Rudziankoŭ

Reputation: 11251

Spring MVC: correct exception handling

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?

Upvotes: 0

Views: 1279

Answers (3)

Maksim Prabarshchuk
Maksim Prabarshchuk

Reputation: 500

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;
 }

Upvotes: 1

Vasu
Vasu

Reputation: 22422

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";
    }

Upvotes: 0

Niku Hysa
Niku Hysa

Reputation: 76

Try the following

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

Upvotes: 0

Related Questions