[英]Spring MVC: correct exception handling
我想知道如何將異常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
正常工作,我忘了做什么?
嘗試做這樣的事情:
@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception ex) {
ModelAndView model = new ModelAndView("error_screen");
model.addAttribute("error", "Exception happened");
return model;
}
嘗試以下
@ExceptionHandler(Exception.class) -> @ExceptionHandler({Exception.class})
原因是它在嘗試調用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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.