一 基本异常处理
SpringBoot2.x配置全局异常实战
讲解:服务端异常讲解和SpringBoot配置全局异常实战
1、默认异常测试 int i = 1/0,不友好
2、异常注解介绍
@ControllerAdvice
如果是返回json数据 则用RestControllerAdvice
,就可以不加@ResponseBody
//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
- 示例代码
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
@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;
}
}
- 测试
@RequestMapping(value = "/api/v1/test_ext")
public Object index(){
int i = 1 / 0;
return new User(11, "dfdf", "1000",new Date());
}
我们访问该接口后会报异常,并被RestControllerAdvice
注解的类捕获,我们在handleException
中处理所有的异常,并返回相应的json格式的数据给前端。
二 自定义异常
SpringBoot2.x配置全局异常返回自定义页面
简介:使用SpringBoot自定义异常和错误页面跳转实战
·
1、返回自定义异常界面,需要引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、resource目录下新建templates,并新建error.html
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;
- 示例代码
- 自定义异常类 MyException.java
package net.lhwclass.demo2.domain;
public class MyException extends RuntimeException {
private String code;
private String msg;
public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 错误处理逻辑
/***
* 处理自定义异常, 并跳转到制定的错误页面
* @param e
* @param request
* @return
*/
@ExceptionHandler(value=MyException.class)
//@ResponseBody
Object handleException(MyException e,HttpServletRequest request){
// 使用modelAndView是返回给前台一个特定的页面,进行页面跳转
// 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", 404);
map.put("msg", e.getMsg());
map.put("url", request.getRequestURL());
return map;
}
- 项目结构