SpringBoot --处理异常跳转错误界面

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实现一个枚举类的实例,打印对于的错误信息到前端界面。
这样在传入数据的时候直接给个判断就能是否需要抛出异常,需要的时候手动抛出,就能实现页面上显示异常了。。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值