1.异常跳转
首先项目在遇到错误,找不到网页,服务器报错的时候,首先会跳转到resources 文件夹里面的templates的 error.html网页文件
可以定义一个错误页面在这个文件夹,如 :
(接受服务器传过来的错误信息${message})
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>广东金融学院</title>
<meta http-equiv="Content-Type" content="/text/html; charset=UTF-8" />
<link rel="stylesheet" href="/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/css/community.css"/>
<link rel="stylesheet" href="/css/bootstrap-theme.min.css">
<script src="/js/jquery-3.4.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</head>
<body>
<div th:insert="~{navigation :: nav}"></div>
<div class="jumbotron">
<h1>出错啦!!</h1>
<p th:text="${message}">服务太热了,要不然稍等下再来试试</p>
<p><a class="btn btn-primary btn-lg" href="/" role="button">回到主页</a></p>
</div>
</body>
</html>
2.服务端新建Handler类来处理错误界面的跳转
类实现@ControllerAdvice注解
以及方法上面定义 @ExceptionHandler注解
package com.gudf.community.Advice;
import com.gudf.community.exception.CustomizeException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class CustomizeExceptionHandler {
@ExceptionHandler(Exception.class)
ModelAndView handle(Throwable e, Model model){
if(e instanceof CustomizeException){
model.addAttribute("message",e.getMessage());
}else {
model.addAttribute("message","服务冒烟了,要不让你稍后再试试");
}
return new ModelAndView("error");
}
}
其中Throwable实现一个枚举类的实例,打印对于的错误信息到前端界面。
这样在传入数据的时候直接给个判断就能是否需要抛出异常,需要的时候手动抛出,就能实现页面上显示异常了。。