本系列文章都是基于SpringBoot2.2.5.RELEASE
自定义异常类
public class HtmlException extends Exception {
public HtmlException(String message) {
super(message);
}
}
public class JsonException extends Exception {
public JsonException(String message) {
super(message);
}
}
编写Controller
@Controller
public class HelloController {
@GetMapping("/hello/{type}")
public String hello(@PathVariable String type) throws Exception {
if ("1".equals(type)) {
throw new HtmlException("抛出异常,返回HTML页面");
} else if ("2".equals(type)) {
throw new JsonException("抛出异常,返回JSON页面");
}
return "hello";
}
}
统一异常处理
创建全局异常处理类:通过使用@ControllerAdvice
定义统一的异常处理类。
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 捕获HtmlException,统一返回错误的HTML页面
*/
@ExceptionHandler(value = HtmlException.class)
public ModelAndView htmlErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("message", e.getMessage());
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
/**
* 捕获JsonException,统一返回JSON数据
*/
@ExceptionHandler(value = JsonException.class)
@ResponseBody
public Object jsonErrorHandler(HttpServletRequest req, Exception e) throws Exception {
Map<String, Object> result = new HashMap<>();
result.put("code","error");
result.put("message",e.getMessage());
return result;
}
}
error.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>统一异常处理</title>
</head>
<body>
<h1 style="text-align: center">统一异常处理</h1>
<div th:text="${url}"></div>
<div th:text="${message}"></div>
</body>
</html>