簡體   English   中英

Spring MVC:正確的異常處理

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM