SpringBoot 利用thymeleaf自定义错误页面

导入thymeleaf


  org.springframework.boot
  spring-boot-starter-thymeleaf

自定义异常类

建立监听异常类

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 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




  
  Title


出异常了

错误信息:

// 获取变量 错误状态码:

失败API地址:

使用

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

效果

SpringBoot 利用thymeleaf自定义错误页面_第1张图片

以上就是SpringBoot 利用thymeleaf自定义错误页面的详细内容,更多关于SpringBoot 自定义错误页面的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(SpringBoot 利用thymeleaf自定义错误页面)