参考资料
- springboot继承AbstractErrorController实现全局的异常处理
https://blog.csdn.net/qq_29684305/article/details/82286469- spring boot 原生错误处理ErrorController
https://blog.csdn.net/shenyunsese/article/details/53390116- @ControllerAdvice 拦截异常并统一处理
https://my.oschina.net/langwanghuangshifu/blog/2246890
在springboot项目中当我们访问一个不存在的url时经常会出现以下页面
在postman访问时则是以下情况
image
对于上面的情况究竟是什么原因造成呢,实际上当springboot项目出现异常时,默认会跳转到/error,而/error则是由BasicErrorController进行处理,其代码如下
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
this(errorAttributes, errorProperties, Collections.emptyList());
}
public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List errorViewResolvers) {
super(errorAttributes, errorViewResolvers);
Assert.notNull(errorProperties, "ErrorProperties must not be null");
this.errorProperties = errorProperties;
}
public String getErrorPath() {
return this.errorProperties.getPath();
}
@RequestMapping(
produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView == null ? new ModelAndView("error", model) : modelAndView;
}
@RequestMapping
@ResponseBody
public ResponseEntity
下面是自己写的一个ErrorController
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import com.xuecheng.framework.model.response.ErrorCode;
import com.xuecheng.framework.model.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* web错误 全局处理
* @author jiangwf
*
*/
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
@Controller
public class InterfaceErrorController implements ErrorController {
private static final String ERROR_PATH="/error";
private ErrorAttributes errorAttributes;
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@Autowired
public InterfaceErrorController(ErrorAttributes errorAttributes) {
this.errorAttributes=errorAttributes;
}
/**
* web页面错误处理
*/
@RequestMapping(value=ERROR_PATH,produces="text/html")
@ResponseBody
public String errorPageHandler(HttpServletRequest request,HttpServletResponse response) {
ServletWebRequest requestAttributes = new ServletWebRequest(request);
Map<String, Object> attr = this.errorAttributes.getErrorAttributes(requestAttributes, false);
JSONObject jsonObject = new JSONObject();
ErrorCode errorCode = new ErrorCode(false, (int) attr.get("status"), (String) attr.get("message"));
return JSONObject.toJSONString(errorCode);
}
/**
* 除web页面外的错误处理,比如json/xml等
*/
@RequestMapping(value=ERROR_PATH)
@ResponseBody
public ResultCode errorApiHander(HttpServletRequest request) {
ServletWebRequest requestAttributes = new ServletWebRequest(request);
Map<String, Object> attr=this.errorAttributes.getErrorAttributes(requestAttributes, false);
return new ErrorCode(false, (int)attr.get("status"), (String) attr.get("message"));
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
@ToString
@Data
@AllArgsConstructor
public class ErrorCode implements ResultCode{
private boolean success;
private int code;
private String message;
@Override
public boolean success() {
return false;
}
@Override
public int code() {
return 0;
}
@Override
public String message() {
return null;
}
}
public interface ResultCode {
//操作是否成功,true为成功,false操作失败
boolean success();
//操作代码
int code();
//提示信息
String message();
}
问题:
解决方法:
异常处理流程
系统对异常的处理使用统一的异常处理流程:
异常抛出及处理流程
image
下面就开始我们的异常处理编程
一、可预知异常
import com.xuecheng.framework.model.response.ResultCode;
import jdk.nashorn.internal.objects.annotations.Getter;
/**
* @Author: jiangweifan
* @Date: 2019/3/4 20:06
* @Description:
*/
public class CustomException extends RuntimeException {
private ResultCode resultCode;
public CustomException(ResultCode resultCode) {
super("错误代码:" + resultCode.code()+" 错误信息:" + resultCode.message());
this.resultCode = resultCode;
}
public ResultCode getResultCode() {
return resultCode;
}
}
import com.xuecheng.framework.model.response.ResultCode;
/**
* @Author: jiangweifan
* @Date: 2019/3/4 20:09
* @Description:
*/
public class ExceptionCast {
public static void cast(ResultCode resultCode, boolean condition) {
if (condition) {
throw new CustomException(resultCode);
}
}
}
import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.net.SocketTimeoutException;
/**
* @Author: jiangweifan
* @Date: 2019/3/4 20:13
* @Description:
*/
@ControllerAdvice
@Slf4j
public class ExceptionCatch {
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult customException(CustomException e) {
log.error("catch exception : {} \r\nexception", e.getMessage(), e);
ResponseResult responseResult = new ResponseResult(e.getResultCode());
return responseResult;
}
}
4.1 定义响应数据格式
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @Author: mrt.
* @Description:
* @Date:Created in 2018/1/24 18:33.
* @Modified By:
*/
@Data
@ToString
@NoArgsConstructor
public class ResponseResult implements Response {
//操作是否成功
boolean success = SUCCESS;
//操作代码
int code = SUCCESS_CODE;
//提示信息
String message;
public ResponseResult(ResultCode resultCode){
this.success = resultCode.success();
this.code = resultCode.code();
this.message = resultCode.message();
}
public static ResponseResult SUCCESS(){
return new ResponseResult(CommonCode.SUCCESS);
}
public static ResponseResult FAIL(){
return new ResponseResult(CommonCode.FAIL);
}
}
其中Response代码如下
public interface Response {
public static final boolean SUCCESS = true;
public static final int SUCCESS_CODE = 10000;
}
4.2 定义错误代码(ResultCode上文已给出)
import com.xuecheng.framework.model.response.ResultCode;
import lombok.ToString;
/**
* Created by mrt on 2018/3/5.
*/
@ToString
public enum CmsCode implements ResultCode {
CMS_ADDPAGE_EXISTSNAME(false,24001,"页面名称已存在!"),
CMS_GENERATEHTML_DATAURLISNULL(false,24002,"从页面信息中找不到获取数据的url!"),
CMS_GENERATEHTML_DATAISNULL(false,24003,"根据页面的数据url获取不到数据!"),
CMS_GENERATEHTML_TEMPLATEISNULL(false,24004,"页面模板为空!"),
CMS_GENERATEHTML_HTMLISNULL(false,24005,"生成的静态html为空!"),
CMS_GENERATEHTML_SAVEHTMLERROR(false,24005,"保存静态html出错!"),
CMS_COURSE_PERVIEWISNULL(false,24007,"预览页面为空!"),
CMS_TEMPLATEFILE_ERROR(false,24008,"模板文件需要.ftl后缀!"),
CMS_TEMPLATEFILE_NULL(false,24009,"模板文件为空!"),
CMS_TEMPLATEFILE_EXCEPTION(false,24010,"解析模板文件异常!"),
CMS_TEMPLATEFILE_FAIL(false,24011,"模板文件存储失败!"),
CMS_TEMPLATEFILE_DELETE_ERROR(false,24012,"模板文件删除失败!"),
CMS_Config_NOTEXISTS(false,24013,"不存在该数据模型!"),
CMS_PAGE_NULL(false,24014,"不存在该页面数据!"),
CMS_GENERATEHTML_CONTENT_FAIL(false,24014,"获取页面模板失败!");
//操作代码
boolean success;
//操作代码
int code;
//提示信息
String message;
private CmsCode(boolean success, int code, String message){
this.success = success;
this.code = code;
this.message = message;
}
@Override
public boolean success() {
return success;
}
@Override
public int code() {
return code;
}
@Override
public String message() {
return message;
}
}
@GetMapping("/list/{page}/{size}")
public QueryResponseResult findList(@PathVariable("page") int page, @PathVariable("size")int size, QueryPageRequest queryPageRequest) {
ExceptionCast.cast(CmsCode.CMS_COURSE_PERVIEWISNULL, queryPageRequest == null);
return pageService.findList(page,size,queryPageRequest);
}
最终方法得到以下结果
image
二、不可预知异常处理
import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.net.SocketTimeoutException;
/**
* @Author: jiangweifan
* @Date: 2019/3/4 20:13
* @Description:
*/
@ControllerAdvice
@Slf4j
public class ExceptionCatch {
//使用EXCEPTIOS存放异常类型 和错误代码的映射,ImmutableMap的特点是已创建就不可变,并且线程安全
private static ImmutableMap, ResultCode> EXCEPTIOS;
//是由builder来构建一个异常类型和错误代码的映射
private static ImmutableMap.Builder, ResultCode> builder =
ImmutableMap.builder();
static {
//初始化基础类型异常与错误代码的映射
builder.put(NullPointerException.class, CommonCode.NULL);
builder.put(SocketTimeoutException.class, CommonCode.NULL);
}
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult customException(CustomException e) {
log.error("catch exception : {} \r\nexception", e.getMessage(), e);
ResponseResult responseResult = new ResponseResult(e.getResultCode());
return responseResult;
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception e) {
log.error("catch exception : {} \r\nexception", e.getMessage(), e);
if (EXCEPTIOS == null) {
EXCEPTIOS = builder.build();
}
final ResultCode resultCode = EXCEPTIOS.get(e.getClass());
if (resultCode != null) {
return new ResponseResult(resultCode);
} else {
return new ResponseResult(CommonCode.SERVER_ERROR);
}
}
}
import lombok.ToString;
/**
* @Author: mrt.
* @Description:
* @Date:Created in 2018/1/24 18:33.
* @Modified By:
*/
@ToString
public enum CommonCode implements ResultCode{
SUCCESS(true,10000,"操作成功!"),
FAIL(false,19999,"操作失败!"),
UNAUTHENTICATED(false,10001,"此操作需要登陆系统!"),
UNAUTHORISE(false,10002,"权限不足,无权操作!"),
NULL(false,10003,"空值异常!"),
TIMEOUT(false, 10004, "服务器连接超时!"),
SERVER_ERROR(false,99999,"抱歉,系统繁忙,请稍后重试!");
// private static ImmutableMap codes ;
//操作是否成功
boolean success;
//操作代码
int code;
//提示信息
String message;
private CommonCode(boolean success,int code, String message){
this.success = success;
this.code = code;
this.message = message;
}
@Override
public boolean success() {
return success;
}
@Override
public int code() {
return code;
}
@Override
public String message() {
return message;
}
}
@GetMapping("/list/{page}/{size}")
public QueryResponseResult findList(@PathVariable("page") int page, @PathVariable("size")int size, QueryPageRequest queryPageRequest) {
int a= 1/0;
return pageService.findList(page,size,queryPageRequest);
}
浏览器访问结果如下:
image
至此我们完成了对全局异常的处理
欢迎关注公众号,后续文章更新通知,一起讨论技术问题 。