2016-07-18 65 views
0

我想知道如何绑定例外handling methodurl mapping方法:Spring MVC的:正确的异常处理

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

我故意挑起java.lang.ArrayIndexOutOfBoundsExceptionusers方法。但我看到handleAllException方法没有执行。

问题: 我忘了做什么使Exception Handling工作适当吗?

+0

我认为你试图使用注解'@ ModelAttribute'不正确。请尝试类似于: '@ExceptionHandler(Exception.class) public ModelAndView handleError(Exception exception){ //代码 return new ModelAndView(“error”); }' – NguaCon

+0

谢谢@NguaCon!这是正确的和有益的。 –

回答

1

尝试做somedthing这样的:

@ExceptionHandler(Exception.class) 
public ModelAndView handleAllException(Exception ex) { 
    ModelAndView model = new ModelAndView("error_screen"); 
    model.addAttribute("error", "Exception happened"); 
    return model; 
} 
0

尝试使用以下

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

这个数组声明不是必需的,只有当我们有更多的那个异常类时它才需要 – rajadilipkolli

0

原因是试图调用的handleAllException()方法它未能通过以下例外:

DEBUG [HTTP-NIO-8080-EXEC-6] --- ExceptionHandlerExceptionResolver:无法调用@ExceptionHandler方法:public java.lang.String controllers.handleAllException(java.lang.Exception,org.springframework.ui.ModelMap) java.lang.IllegalStateException:没有合适的参数解析器[1] [type = org.springframework.ui.ModelMap] 个HandlerMethod细节:

更改方法如下:

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