SpringBoot默认的处理异常的机制:SpringBoot 默认的已经提供了一套处理异常的机制。一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 springBoot 中提供了一个叫 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息
如 果我 们 需 要 将 所 有 的 异 常 同 一 跳 转 到 自 定 义 的 错 误 页 面 , 需 要 在src/main/resources/templates 目录下创建 error.html 页面。注意:名称必须叫 error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
出错了,请与管理员联系。。。
</body>
</html>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
package cn.fpl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DemoController {
@RequestMapping("/show1")
public String show1(){
String str = null;
str.length();
return "index";
}
@RequestMapping("/show2")
public String show2(){
int a = 6/0;
return "index";
}
}
然后重新启动后异常页面变为:
创建一个exception包在其中创建一个GlobaleExceptionHandler.java
package cn.fpl.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class GlobaleExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv = new ModelAndView();
if(e instanceof NullPointerException){
mv.setViewName("error1");
}else if(e instanceof ArithmeticException){
mv.setViewName("error2");
}
mv.addObject("msg", e.toString());
return mv;
}
}
error1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-ArithmeticException</title>
</head>
<body>
<h2>error1</h2>
出错了,请与管理员联系。。。
<span th:text="${msg}"></span>
</body>
</html>
error2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-ArithmeticException</title>
</head>
<body>
<h2>error2</h2>
出错了,请与管理员联系。。。
<span th:text="${msg}"></span>
</body>
</html>
/*
* Copyright (c) 2020, 2024, fpl1116.cn All rights reserved.
*
*/
package cn.fpl.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Project: SpringBootDemo - AjaxGlobalException</p>
* <p>Powered by fpl1116 On 2024-01-15 10:48:48</p>
* <p>描述:<p>
*
* @author fpl1116 [2391940642@qq.com]
* @version 1.0
* @since 1.8
*/
@ControllerAdvice
public class AjaxGlobalException {
@ResponseBody
@ExceptionHandler
public Map errorHandler(Exception e){
Map<String, Object> map = new HashMap<>();
map.put("status", 500);
map.put("msg", e.toString());
return map;//{status:500, msg:异常信息}
}
}