异常注解介绍:
@ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody
/捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class
1.自定义异常类:可以选择不同的返回方式:(1)返回页面,(2)返回json数据
package com.study.studyBoot.util; import com.study.studyBoot.model.JsonData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @Description: 自定义异常类,需要继承RuntimeException接口,出现异常的时候ExceptionHandler会进行异常的匹配 * @author: panboyang * @date :2019-06-29 10:44:05 * @params: No such property: code for class: Script1 */ @RestControllerAdvice public class myException extends RuntimeException{ private static final Logger log = LoggerFactory.getLogger(myException.class); /** * @Description: 返回页面 * @author: panboyang * @date :2019-06-29 11:26:41 * @params: No such property: code for class: Script1 */ @ExceptionHandler(value =ArithmeticException.class ) public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{ e.printStackTrace();//打印异常信息 log.info("进入异常类"); ModelAndView mv = new ModelAndView(); mv.addObject("exception",e); mv.addObject("url",request.getRequestURL());//发生异常的路径 mv.setViewName("error.html");//指定发生异常之后跳转页面 return mv; } /** * @Description: 返回json * @author: panboyang * @date :2019-06-29 11:26:19 * @params: No such property: code for class: Script1 */ @ExceptionHandler(value = Exception.class) public JsonData errorException(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{ e.printStackTrace();//打印异常信息 log.info("进入异常类"); return new JsonData(1,"测试错误数据返回"); } }
2.自定义异常的页面;根据需要自己定义
注意:
1、返回自定义异常界面,需要引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、resource目录下新建templates,并新建error.html(根据需要自己定义)
3.测试异常:
@GetMapping("/testexception") public void testexception(){ int a = 1/0; } @GetMapping("/testexceptionJson") public void testexceptionJson() throws Exception { throw new Exception(); }