gpt4 book ai didi

java - Spring MVC : correct exception handling

转载 作者:行者123 更新时间:2023-12-01 09:41:07 25 4
gpt4 key购买 nike

我想知道如何将异常处理方法绑定(bind)到url映射方法:

@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 方法没有执行。

问题:为了让异常处理正常工作,我忘记做什么?

最佳答案

尝试做这样的事情:

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

关于java - Spring MVC : correct exception handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38433419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com