有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringMVC:正确的异常处理

我想知道如何将异常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";
    }
}

我故意在{}方法中激发{}。但是我看到handleAllException方法没有被执行

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


共 (3) 个答案

  1. # 1 楼答案

    试着做这样的事情:

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

    原因是它在尝试调用handleAllException()方法时失败,出现以下异常:

    调试[http-nio-8080-exec-6]-ExceptionHandlerExceptionResolver:未能调用@ExceptionHandler方法:公共java。字符串控制器。handleAllException(java.lang.Exception,org.springframework.ui.ModelMap) JAVAlang.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";
        }
    
  3. # 3 楼答案

    试试下面的方法

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