【问题标题】:Spring MVC: correct exception handlingSpring MVC:正确的异常处理
【发布时间】:2016-07-18 09:42:34
【问题描述】:

我想知道如何将异常handling method绑定到url mapping方法:

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

我故意在users方法中挑衅java.lang.ArrayIndexOutOfBoundsException。但是我看到 handleAllException 方法没有被执行。

问题: 我忘记做什么才能使Exception Handling 正常工作?

【问题讨论】:

  • 我认为您尝试错误地使用注释@ModelAttribute。请尝试类似的方法: ` @ExceptionHandler(Exception.class) public ModelAndView handleError(Exception exception) { //这里的代码 return new ModelAndView("error"); }`
  • 谢谢你,@NguaCon!这是正确且有用的。

标签: java spring spring-mvc exception-handling


【解决方案1】:

尝试做这样的事情:

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

【讨论】:

    【解决方案2】:

    试试下面的

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

    【讨论】:

    • 这个数组声明不是必须的,只有当我们有多个异常类时才需要它
    【解决方案3】:

    原因是它在尝试调用 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";
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 2016-12-30
      • 2015-01-24
      • 2016-11-18
      相关资源
      最近更新 更多