SpringBoot thymeleaf自定义错误页面

2020-07-21 11:51:54 浏览数 (2)

导入thymeleaf

  • pom.xml
代码语言:javascript复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

自定义异常类

  • 建立监听异常类

MyException.class

代码语言:javascript复制
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 监测异常

代码语言:javascript复制
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

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>出异常了</h1>

<span>错误信息:</span><h1 th:text="${msg}"></h1>    // 获取变量
<span>错误状态码:</span><h1 th:text="${code}"></h1>
<span>失败API地址:</span><h1 th:text="${url}"></h1>
</body>
</html>

使用

代码语言:javascript复制
@RequestMapping("/user_info")
    public Map<String, String> testMap() {
        throw new MyException(500, "手动抛出");
    }

效果

0 人点赞