本篇文章给大家分享的是有关SpringBoot中的错误页面如何使用thymeleaf实现自定义,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
导入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
自定义异常类
建立监听异常类
MyException.class
package com.example.demo.domain;
public class MyException extends RuntimeException {
private int code;
private String msg;
public MyException(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
CustomExtHandle 监测异常
package com.example.demo.domain;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
@RestControllerAdvice
public class CustomExtHandle {
// 捕获全局异常
@ExceptionHandler(value = Exception.class)
Object handleException(Exception e, HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
// 如果是Myexception类
@ExceptionHandler(value = MyException.class)
Object handleMyException(MyException e, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html"); // 指定错误跳转页面 需要在templates里面新建 一个error.html
modelAndView.addObject("msg", e.getMsg());
modelAndView.addObject("code", e.getCode());
modelAndView.addObject("url", request.getRequestURL());
return modelAndView;
// 当然这里也可以返回json数据 前后台分离的话直接返回一个json即可
}
}
template/error.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>出异常了</h2>
<span>错误信息:</span><h2 th:text="${msg}"></h2> // 获取变量
<span>错误状态码:</span><h2 th:text="$[code]"></h2>
<span>失败API地址:</span><h2 th:text="${url}"></h2>
</body>
</html>
使用
@RequestMapping("/user_info")
public Map<String, String> testMap() {
throw new MyException(500, "手动抛出");
}
效果
以上就是SpringBoot中的错误页面如何使用thymeleaf实现自定义,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。