个人推荐第二种, 第一种不会正确打印url
第一种:
package com.springboot.common.controller;
import com.springboot.common.enumerate.HttpStatusEnum;
import com.springboot.common.pojo.Error;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
* 如果使用GlobalExceptionHandler就注释掉该类
* @Auther: quleou
* @Date: 2018/8/28 13:41
* @Description:
*/
//@Controller //使用请打开注释
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {
private static final String DEFAULT_ERROR_MESSAGE = "服务繁忙,请稍后再试!";
private static final String errorDir = "error/";
@Override
public String getErrorPath() {
return "default";
}
@RequestMapping(value = "/error")
public String error(Model model, HttpServletRequest request, HttpServletResponse response, Exception e) {
// 自定义的Error
Error error = new Error();
// 自定义Http状态码枚举
HttpStatusEnum httpStatusEnum = HttpStatusEnum.valueOf(response.getStatus());
// 异常信息
error.setMessage(getErrorMessage(httpStatusEnum));
// 异常url
error.setUrl(new String(request.getRequestURL()));
// 异常时间
error.setTimestamp( new Date().toString());
// 异常状态码
error.setStatus(httpStatusEnum.code());
model.addAttribute("error", error);
String errorPath = getErrorPath();
// 处理跳转页面
switch (httpStatusEnum.code()) {
case 404:
errorPath = errorDir + "404";
break;
case 500:
errorPath = errorDir + "500";
break;
default:
errorPath = errorDir + errorPath;
}
return errorPath;
}
// 根据状态码获得返回消息
public static String getErrorMessage(HttpStatusEnum httpStatusEnum) {
if (httpStatusEnum == null)
return DEFAULT_ERROR_MESSAGE;
return httpStatusEnum.reasonPhraseUS() + " " + httpStatusEnum.reasonPhraseCN();
}
}
第二种:
BaseGlobalExceptionHandler 父类
package com.springboot.common.handler;
import com.google.common.base.Throwables;
import com.springboot.common.enumerate.HttpStatusEnum;
import com.springboot.common.pojo.Error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* @Auther: quleou
* @Date: 2018/8/28 10:20
* @Description:
*/
public class BaseGlobalExceptionHandler {
protected static final Logger logger = null;
prote