一、背景
前端返回页面不要出现404、500等tomcat或SpringBoot专属的异常页面。
二、环境
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
三、代码
1.先创建异常实体类
public class ErrorInfo {
/** 发生时间 */
private String time;
/** 访问Url */
private String url;
/** 错误类型 */
private String error;
/** 错误的堆栈轨迹 */
String stackTrace;
/** 状态码 */
private int statusCode;
/** 原因短语 */
private String reasonPhrase;
//getter and setter
}
- 统一异常信息的构建工具
ErrorInfoBuilder 作为核心工具类,其意义不言而喻,重点API:- 获取错误/异常
- 通信状态
- 堆栈轨迹
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class ErrorInfoBuilder implements HandlerExceptionResolver, Ordered {
/**
* 错误KEY
*/
private final static String ERROR_NAME = "doudou.error";
/**
* 错误配置(ErrorConfiguration)
*/
private ErrorProperties errorProperties;
public ErrorProperties getErrorProperties() {
return errorProperties;
}
public void setErrorProperties(ErrorProperties errorProperties) {
this.errorProperties = errorProperties;
}
/**
* 错误构造器 (Constructor) 传递配置属性:server.xx -> server.error.xx
*/
public ErrorInfoBuilder(ServerProperties serverProperties) {
this.errorProperties = serverProperties.getError();
}
/**
* 构建错误信息.(ErrorInfo)
*/
public ErrorInfo getErrorInfo(HttpServletRequest request) {
return getErrorInfo(request, getError(request));
}
/**
* 构建错误信息.(ErrorInfo)
*/
public ErrorInfo getErrorInfo(HttpServletRequest request, Throwable error) {
ErrorInfo errorInfo = new ErrorInfo();
errorInfo.setTime(LocalDateTime.now().toString());
errorInfo.setUrl(request.getRequestURL().toString());
errorInfo.setError(error.toString());
errorInfo.setStatusCode(getHttpStatus(request).value());
errorInfo.setReasonPhrase(getHttpStatus(request).getReasonPhrase());
errorInfo.setStackTrace(getStackTraceInfo(error, isIncludeStackTrace(request)));
return errorInfo;
}
/**
* 获取错误.(Error/Exception)
* @see DefaultErrorAttributes #addErrorDetails
*/
public Throwable getError(HttpServletRequest request) {
//根据HandlerExceptionResolver接口方法来获取错误.
Throwable error = (Throwable) request.getAttribute(ERROR_NAME);
//根据Request对象获取错误.
if (error == null) {
error = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE);
}
//当获取错误非空,取出RootCause.
if (error != null) {
while (error instanceof ServletException && error.getCause() != null) {
error = error.getCause();
}
}
//当获取错误为null,此时我们设置错误信息即可.
else {
String message = (String) request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE);
if (StringUtils.isEmpty(message)) {
HttpStatus status = getHttpStatus(request);
message = "Unknown Exception But " + status.value() + " " + status.getReasonPhrase();
}
error = new Exception(message);
}
return error;
}
/**
* 获取通信状态(HttpStatus)
* @see AbstractErrorController #getStatus
*/
public HttpStatus getHttpStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE);
try {
return statusCode != null ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR;
} catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
/**
* 获取堆栈轨迹(StackTrace)
* @see DefaultErrorAttributes #addStackTrace
*/
public String getStackTraceInfo(Throwable error, boolean flag) {
if (!flag) {
return "omitted";
}
StringWriter stackTrace = new StringWriter();
error.printStackTrace(new PrintWriter(stackTrace));
stackTrace.flush();
return stackTrace.toString();
}
/**
* 判断是否包含堆栈轨迹.(isIncludeStackTrace)
* @see BasicErrorController #isIncludeStackTrace
*/
public boolean isIncludeStackTrace(HttpServletRequest request) {
//读取错误配置(server.error.include-stacktrace=NEVER)
ErrorProperties.IncludeAttribute includeStacktrace = errorProperties.getIncludeStacktrace();
//情况1:若IncludeStacktrace为ALWAYS
if (includeStacktrace == ErrorProperties.IncludeAttribute.ALWAYS) {
return true;
}
//情况2:若请求参数含有trace
if (includeStacktrace == ErrorProperties.IncludeAttribute.ON_PARAM) {
String parameter = request.getParameter("trace");
return parameter != null && !"false".equals(parameter.toLowerCase());
}
//情况3:其它情况
return false;
}
/**
* 保存错误/异常.
* @see DispatcherServlet #processHandlerException 进行选举HandlerExceptionResolver
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
request.setAttribute(ERROR_NAME, ex);
return null;
}
/**
* 提供优先级 或用于排序
*/
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
- 全局异常请求控制层
@Controller
@RequestMapping("${server.error.path:/error}")
public class GlobalErrorController implements ErrorController {
/** 错误信息的构建工具. */
@Autowired
private ErrorInfoBuilder errorInfoBuilder;
/** 错误信息页 */
private final static String DEFAULT_ERROR_VIEW = "error";
/**
* 情况1:若预期返回类型为text/html,则返回错误信息页(View).
*/
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request) {
return new ModelAndView(DEFAULT_ERROR_VIEW, "errorInfo", errorInfoBuilder.getErrorInfo(request));
}
/**
* 情况2:其它预期类型 则返回详细的错误信息(JSON).
* BaseDto 是所有接口返回给前端的对象
*/
@RequestMapping
@ResponseBody
public BaseDto error(HttpServletRequest request, HttpServletResponse response) {
ErrorInfo errorInfo = errorInfoBuilder.getErrorInfo(request);
BaseDto baseDto;
switch (errorInfo.getStatusCode()) {
case 500:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "服务器错误,服务器在处理请求的过程中发生了错误");
break;
case 501:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "服务器不支持请求的功能,无法完成请求");
break;
case 502:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "作为网关或者代理工作的服务器尝试执行请求时,从远程服务器接收到了一个无效的响应");
break;
case 400:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "客户端请求的语法错误,服务器无法理解");
break;
case 401:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "请求要求用户的身份认证");
break;
case 403:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "服务器理解请求客户端的请求,但是拒绝执行此请求");
break;
case 404:
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "服务器无法根据客户端的请求找到资源(网页)。");
break;
default:
if (errorInfo.getStatusCode() < 200) {
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "信息,服务器收到请求,需要请求者继续执行操作");
break;
}
if (errorInfo.getStatusCode() < 300) {
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "成功,操作被成功接收并处理");
break;
}
if (errorInfo.getStatusCode() < 400) {
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "重定向,需要进一步的操作以完成请求");
break;
}
if (errorInfo.getStatusCode() < 500) {
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "客户端错误,请求包含语法错误或无法完成请求");
break;
}
if (errorInfo.getStatusCode() < 600) {
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "服务器错误,服务器在处理请求的过程中发生了错误");
break;
}
baseDto = BaseDto.genBaseDto(CommonConstant.HttpStatus.FAIL.getStatus(), "其他错误");
}
response.setStatus(200);
return baseDto;
}
}