软件编程
位置:首页>> 软件编程>> java编程>> SpringBoot 利用thymeleaf自定义错误页面

SpringBoot 利用thymeleaf自定义错误页面

作者:憧憬  发布时间:2023-11-29 08:29:55 

标签: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>
<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>

使用


@RequestMapping("/user_info")
 public Map<String, String> testMap() {
   throw new MyException(500, "手动抛出");
 }

效果

SpringBoot 利用thymeleaf自定义错误页面

来源:https://aoppp.com/springboot-thymeleaf-zi-ding-yi-cuo-wu-y/

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com