自定义错误页面
覆盖错误页面方式
在/resources/templates下面创建error.html就可以覆盖默认的错误页面
代码示例
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
动态error错误页面
<p th:text="${error}"></p>
<p th:text="${status}"></p>
<p th:text="${message}"></p>
</body>
</html>
访问一个不存在的页面
根据不同的状态码返回不同的视图页面,错误页面可以是静态HTML,也可以使用模板构建
静态HTML页面,不带错误信息,在resource/public/下面创建error目录,在error目录下创建对应的状态码html就行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
静态404错误页面
</body>
</html>
访问一个不存在的页面
具体状态码错误页面将覆盖error.html
动态模板页面,带上错误信息,在resources/templates/下面创建error目录,创建具体状态码页面
模拟500错误
package com.zzf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author zzf
* @date 2021-03-09
*/
@Controller
public class BaseErrorController {
@RequestMapping(value = "/ex")
@ResponseBody
public String error() {
int i = 5 / 0;
return "ex";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
动态500错误页面
<p th:text="${error}"></p>
<p th:text="${status}"></p>
<p th:text="${message}"></p>
</body>
</html>
同时存在静态500.html和动态模板的500.html,后者会覆盖前者
对某些错误特殊对待
例如对500错误特殊处理
package com.zzf.config;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
/**
* @author zzf
* @date 2021-03-09
*/
@Configuration
public class ContainerConfig {
/**
* HttpStatus.INTERNAL_SERVER_ERROR对应500错误码
* 如果程序发生500错误,就会将请求转发到/error/500
*
* @return
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> containerCustomizer() {
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
}
};
}
}
@RequestMapping("/error/500")
@ResponseBody
public String showServerError(){
return "server error";
}
这个方法重写了/500映射,但缺点是无法获取错误信息
想要获取错误信息,可以继承BasicErrorController,把/error/500映射方法添加进来,把之前定义的/error/500映射删除
package com.zzf.controller;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* @author zzf
* @date 2021-03-09
*/
@Controller
public class MyBasicErrorController extends BasicErrorController {
public MyBasicErrorController() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
@RequestMapping(produces = "text/html", value = "/500")
//定义500的视图
public ModelAndView errorHtml500(HttpServletRequest request, HttpServletResponse response) {
response.setStatus(getStatus(request).value());
Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
model.put("msg", "自定义错误");
return new ModelAndView("error/500", model);
}
@RequestMapping(value = "/500")
@ResponseBody
public ResponseEntity<Map<String, Object>> error500(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}
}
在动态模板页面加一行显示自定义信息
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
动态500错误页面
<p th:text="${error}"></p>
<p th:text="${status}"></p>
<p th:text="${message}"></p>
<p th:text="${msg}"></p>
</body>
</html>
利用ExceptionHandler进行局部异常处理,捕获除0异常
package com.zzf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author zzf
* @date 2021-03-09
*/
@Controller
public class BaseErrorController {
@RequestMapping(value = "/ex")
@ResponseBody
public String error() {
int i = 5 / 0;
return "ex";
}
//局部异常处理
@ExceptionHandler(Exception.class)
@ResponseBody
public String exHandler(Exception e) {
if (e instanceof ArithmeticException) {
return "发生了除0异常";
}
return "发生了未知异常";
}
}
SpringBoot简单全局异常类
定义业务异常类
package com.zzf.error;
/**
* @author zzf
* @date 2021-03-09
*/
public class BusinessException extends RuntimeException {
public BusinessException() {
}
public BusinessException(String message) {
super(message);
}
}
错误信息类
package com.zzf.error;
import lombok.Data;
/**
* @author zzf
* @date 2021-03-09
*/
@Data
public class ErrorInfo<T> {
public static final Integer SUCCESS = 200;
public static final Integer ERROR = 100;
//错误信息
private Integer code;
private String message;
private String url;
private T data;
}
异常处理类
package com.zzf.error;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* 统一业务异常处理类
*
* @author zzf
* @date 2021-03-09
*/
@ControllerAdvice(basePackages = {"com.zzf",})
public class GlobalDefaultExceptionHandler {
@ExceptionHandler(BusinessException.class)
@ResponseBody
public ErrorInfo defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
ErrorInfo errorInfo = new ErrorInfo();
errorInfo.setMessage(e.getMessage());
errorInfo.setUrl(request.getRequestURI());
errorInfo.setCode(ErrorInfo.SUCCESS);
return errorInfo;
}
}
测试
package com.zzf.controller;
import com.zzf.error.BusinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author zzf
* @date 2021-03-09
*/
@Controller
public class MyController {
@RequestMapping("/find")
public String serviceHand() {
throw new BusinessException("业务异常");
}
}
访问后返回json格式的错误信息
参考
https://mp.weixin.qq.com/s/onSfBYZbCBKQWNJC8jwoIQ