Are you sure you want to delete this task? Once this task is deleted, it cannot be recovered.
|
2 years ago | |
---|---|---|
.. | ||
src | 2 years ago | |
README.md | 2 years ago | |
pom.xml | 2 years ago |
此 demo 演示了如何在Spring Boot中进行统一的异常处理,包括了两种方式的处理:第一种对常见API形式的接口进行异常处理,统一封装返回格式;第二种是对模板页面请求的异常处理,统一处理错误页面。
<dependencies>
<dependency>
<groupId>com.xkcoding</groupId>
<artifactId>common-tools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 模板引擎,用于错误页面的展示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
// JSON 异常
@Getter
public class JsonException extends CommonBizException {
public JsonException(IStatus status) {
super(status);
}
public JsonException(Integer code, String message) {
super(code, message);
}
}
// 页面异常
@Getter
public class PageException extends CommonBizException {
public PageException(IStatus status) {
super(status);
}
public PageException(Integer code, String message) {
super(code, message);
}
}
@Slf4j
@ControllerAdvice
public class DemoExceptionHandler {
private static final String DEFAULT_ERROR_VIEW = "error";
/**
* 统一 json 异常处理
*
* @param exception JsonException
* @return 统一返回 json 格式
*/
@ExceptionHandler(value = JsonException.class)
@ResponseBody
public Response<Void> jsonErrorHandler(JsonException exception) {
log.error("【JsonException】:{}", exception.getMessage());
return Response.ofError(exception);
}
/**
* 统一 页面 异常处理
*
* @param exception PageException
* @return 统一跳转到异常页面
*/
@ExceptionHandler(value = PageException.class)
public ModelAndView pageErrorHandler(PageException exception) {
log.error("【PageException】:{}", exception.getMessage());
ModelAndView view = new ModelAndView();
view.addObject("message", exception.getMessage());
view.setViewName(DEFAULT_ERROR_VIEW);
return view;
}
}
位于
src/main/resources/template
目录下
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8"/>
<title>统一页面异常处理</title>
</head>
<body>
<h1>统一页面异常处理</h1>
<div th:text="${message}"></div>
</body>
</html>
@Controller
public class TestController {
@GetMapping("/json")
@ResponseBody
public Response<Void> jsonException() {
throw new JsonException(CommonStatus.SERVER_ERROR);
}
@GetMapping("/page")
public ModelAndView pageException() {
throw new PageException(CommonStatus.SERVER_ERROR);
}
}
启动 ExceptionHandlerApplication
http://localhost:8080/demo/json
,同时观察控制台日志输出http://localhost:8080/demo/page
,同时观察控制台日志输出一个用来深度学习并实战 spring boot 的项目,目前总共包含 66 个集成demo,已经完成 55 个。
Java SVG CSS JavaScript SQL other