在web开发中发生了异常,往往是需要通过一个统一的异常处理来保证客户端能够收到友好的提示。
1、 默认异常机制 :SpringBoot 默认提供了两种机制
1>针对于web浏览器访问的错误页面响应
2>针对于 接口测试工具等的参数响应处理
访问:http://localhost:8089/my/ex1 没有找到页面404错误!
2、自定义json格式异常响应
通过 @ControllerAdvice/@RestControllerAdvice 和 @ExceptionHandler 注解全局异常自定义响应类
操作步骤:
1> 异常处理类
/**
* 全局异常处理
*/
@RestControllerAdvice
public class CustomExtHandler {
private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
//@ResponseBody
Object handleException(Exception e,HttpServletRequest request){
//通过日志跟踪
LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
}
2>Controller类
@RestController
public class ExceptionController {
//处理全局异常
@RequestMapping("/my/ex")
public Object index(){
int i=2/0; //发生异常的哦!
return new Student(11,"john","000");
}
}
测试:
3、自定义异常处理页面
1> 添加*thymeleaf
*依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2> resource目录下新建templates|error.html
<h1>发生了异常哦!!!!!</h1>
3> 自定义异常类
/**
* 功能描述:自定义异常类
*
*/
public class MyException extends RuntimeException {
public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
}
private String code;
private String msg;
...}
4>做错误页面异常处理 返回 ModelAndView
@RestControllerAdvice
public class CustomExtHandler {
//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=MyException.class)
Object handleMyException(MyException e,HttpServletRequest request){
//进行页面跳转
// ModelAndView modelAndView = new ModelAndView();
// modelAndView.setViewName("error.html");
// modelAndView.addObject("msg", e.getMessage());
// return modelAndView;
//返回json数据,由前端去判断加载什么页面
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("msg", e.getMsg());
map.put("url", request.getRequestURL());
return map;
}
}
测试: