Springmvc如何进行异常处理
- 局部处理.
![](https://img2018.cnblogs.com/blog/1782935/201909/1782935-20190905211123350-738423528.png)
1 @ExceptionHandler //当该类中发生异常时有该方法来处理
2 public ModelAndView error(Exception exception) {
3 ModelAndView mv=new ModelAndView();
4 mv.addObject("error", exception.getMessage());
5 mv.setViewName("error");
6 return mv;
7 }
- 定义一个全局异常类。
![](https://img2018.cnblogs.com/blog/1782935/201909/1782935-20190905211212691-678636772.png)
1 package com.zhiyou100.wc.controller;
2
3 import org.springframework.web.bind.annotation.ControllerAdvice;
4 import org.springframework.web.bind.annotation.ExceptionHandler;
5 import org.springframework.web.servlet.ModelAndView;
6
7 @ControllerAdvice
8 public class ExceptionController {
9
10 @ExceptionHandler //当该类中发生异常时有该方法来处理
11 public ModelAndView error(Exception exception) {
12 ModelAndView mv=new ModelAndView();
13 mv.addObject("error", exception.getMessage());
14 mv.setViewName("error");
15 return mv;
16 }
17 }