第一种,直接在Controller层写@ExceptionHandler注解,对于指定异常,可以处理并返回一个视图或者body:
@Controller
public class HelloWorld {
@RequestMapping("test")
public String test(int flag) throws FileNotFoundException {
if (1 == flag) {
throw new FileNotFoundException("文件找不到");
}
if (2 == flag) {
int i = 1 / 0;
}
return "hello";
}
@ExceptionHandler(IOException.class)
public ModelAndView h(Exception e, HttpServletRequest req, HttpServletResponse resp, HttpSession sesseion) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("hello");
modelAndView.addObject("name", e.getMessage());
return modelAndView;
}
@ResponseBody
@ExceptionHandler(ArithmeticException.class)
public String h1(Exception e, HttpServletRequest req, HttpServletResponse resp, HttpSession sesseion) {
return req.getRequestURI() + "抛出异常" + e.getClass().getName() + e.getMessage();
}
}
第二种,全局异常处理,通过@ControllerAdvice对所有Controller进行切面通知,可以指定父类
@ExceptionHandler可以指定父类异常
@ControllerAdvice(assignableTypes = HelloWorld.class)
public class ExceptionHanlderClass {
@ResponseBody
@ExceptionHandler(Exception.class)
public String handleExceptions(Exception e, HttpServletRequest req){
return req.getRequestURI() + "抛出一个异常" + e.getClass().getName() + e.getMessage();
}
}