Springboot 处理异常(三)
程序员文章站
2022-05-03 10:24:05
...
大家在搭建项目时,肯定会有处理异常这个模块。
第一种方式是返回json数据,目前大家都会进行前后端的分离,使用json的居多。
自定义异常处理类,此处
/**
* 异常捕获
*/
@RestControllerAdvice
public class ExceptionCatch {
/**
* 除数为0异常
* @param e
* @param request
* @return
*/
@ExceptionHandler(value=ArithmeticException.class)
public ReponseData numberException(Exception e, HttpServletRequest request){
ReponseData reponseData = new ReponseData();
reponseData.setCode(500);
reponseData.setMsg(e.getMessage());
return reponseData;
}
}
测试
@RestController
@RequestMapping("exception")
public class TestException {
@GetMapping("/test1")
public ReponseData test1(){
ReponseData reponseData = new ReponseData();
int a = 1/0;
return reponseData;
}
}
此时就会捕获到除数为0的异常
第二种就是跳转页面了,这种适用于小型项目,没有进行前后端分离(jsp)
创建webapp、web-inf
修改配置文件
pom引入
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--用于编译jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
异常类
/**
* 异常捕获
*/
@ControllerAdvice
public class ExceptionCatch {
/**
* 除数为0异常
* @param e
* @param request
* @return
*/
@ExceptionHandler(value=ArithmeticException.class)
public ModelAndView numberException(Exception e, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.jsp");
modelAndView.addObject("msg",e.getMessage());
return modelAndView;
}
}
还有一种方式通过html
templates中创建error.html
pom引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
异常类
/**
* 异常捕获
*/
@ControllerAdvice
public class ExceptionCatch {
/**
* 除数为0异常
* @param e
* @param request
* @return
*/
@ExceptionHandler(value=ArithmeticException.class)
public ModelAndView numberException(Exception e, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
return modelAndView;
}
}
上一篇: 自学SpringBoot--05服务端表单数据校验
下一篇: SpringBoot服务端表单数据校验