1.異常處理
public class CustomExceptionHandler {
/**
* 統(tǒng)一異常處理
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
Object handlerException(Exception e,HttpServletRequest request) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("code", "100");
map.put("msg", e.getMessage());
map.put("request", request.getRequestURL());
return map;
}
/**
* 處理自定義異常幻碱,返回異常對(duì)應(yīng)的錯(cuò)誤頁(yè)面
* @param e
* @return
*/
@ExceptionHandler(value = MyException.class)
Object handleMyException(MyException e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMsg());
System.out.println(e.getMsg());
return modelAndView;
}
/**
* 處理自定義異常采桃,返回錯(cuò)誤信息
* @param e
* @param request
* @return
*/
@ExceptionHandler(value = MyException2.class)
Object handleMyException2(MyException2 e,HttpServletRequest request) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("code", "100");
map.put("msg", e.getMsg());
map.put("request", request.getRequestURL());
return map;
}
}
2.MyException陪竿、MyException2根據(jù)需求自己定義
public class MyException extends RuntimeException{
private String code;
private String msg;
public MyException(String code, String msg) {
super();
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;
}
}
3.異常跳轉(zhuǎn)錯(cuò)誤頁(yè)面
1)需要引入依賴
<!-- 使用Thymeleaf視圖構(gòu)建MVC Web應(yīng)用程序的入門 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>springboot html test</title>
</head>
<body>
404 error!
</body>
</html>
4.測(cè)試controller
@RestController
public class ExceptionTestController {
@GetMapping("/test/exp")
Object TestException() {
System.out.println(1/0);
return new User("1", "lxh", "159", new Date());
}
@GetMapping("/test/myexp")
Object TestMyException() {
throw new MyException("101", "my exception test");
}
@GetMapping("/test/myexp2")
Object TestMyException2() {
throw new MyException2("102", "my exception2 test");
}
}