全局异常 import com.alibaba.fastjson.JSON; import com.ziku.msp.common_enum.ErrorCodeEnum; import com.ziku.msp.exception.BizException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.core.Ordered; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.stereotype.Component; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; @Slf4j @Component public class GlobalExceptionHandler implements HandlerExceptionResolver, Ordered { private int order = Ordered.HIGHEST_PRECEDENCE; @Override public int getOrder() { return 0; } @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) { Mapmap = new HashMap (); if (ex instanceof BizException) { log.info("GlobalExceptionHandler>>>>>异常信息:{}", ExceptionUtils.getStackTrace(ex)); BizException runtimeException = (BizException) ex; map.put("errorCode", runtimeException.getErrorCode()); map.put("errorMsg", runtimeException.getErrorMsg()); }else if (ex instanceof HttpRequestMethodNotSupportedException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUEST_METHOD_ERROR.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUEST_METHOD_ERROR.getErrorMsg()); }else if (ex instanceof NoHandlerFoundException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUESTED_URL_DOESNT_EXIST.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUESTED_URL_DOESNT_EXIST.getErrorMsg()); } else if (ex instanceof ServletRequestBindingException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorMsg()); } else if (ex instanceof HttpMessageNotReadableException) { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.REQUEST_PARAMETER_IS_INCORRECT.getErrorMsg()); }else if (ex instanceof ConstraintViolationException) { log.error("-------controller exception-------", ex); final String msg = ((ConstraintViolationException) ex).getConstraintViolations().stream() .map(ConstraintViolation::getMessage) .collect(Collectors.joining(",")); map.put("errorCode", "400"); map.put("errorMsg", msg); } else { log.error("-------controller exception-------", ex); map.put("errorCode", ErrorCodeEnum.INTERNAL_SERVER_ERROR.getErrorCode()); map.put("errorMsg", ErrorCodeEnum.INTERNAL_SERVER_ERROR.getErrorMsg()); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8"); String method = request.getMethod(); String origin = request.getHeader("Origin"); response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Credentials", "true"); //response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域问题 response.setHeader("Access-Control-Allow-Headers", "*"); // 特殊的header需要定义,Content-Type等常用请求头不需要设置加入 response.setHeader("Access-Control-Allow-Methods","*"); response.setStatus(200); try { response.getWriter().print(JSON.toJSONString(map)); } catch (IOException e) { e.printStackTrace(); } return new ModelAndView(); } }
运行时异常的统一封装
public class BizException extends RuntimeException { /** * */ private static final long serialVersionUID = -5110371239340231002L; private String errorCode; private String errorMsg; public BizException(Throwable cause) { super(cause); } public BizException(String message) { super(message); } public BizException(String message, Throwable cause) { super(message, cause); } public BizException(Exception exception) { super(exception); } public BizException(ErrorCodeEnum errorCode, Throwable cause) { super(cause); this.errorCode = errorCode.getErrorCode(); this.errorMsg = errorCode.getErrorMsg(); } public BizException(String errorCode, String errorMsg) { super(); this.errorCode = errorCode; this.errorMsg = errorMsg; } public BizException(ErrorCodeEnum errorCode) { super(); this.errorCode = errorCode.getErrorCode(); this.errorMsg = errorCode.getErrorMsg(); } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } }
定义异常枚举
public enum ErrorCodeEnum { REQUEST_METHOD_ERROR("-3", "接口请求方法类型错误"), REQUEST_PARAMETER_IS_INCORRECT("-2", "请求参数有误"), INTERNAL_SERVER_ERROR("-1", "服务繁忙"), REQUESTED_URL_DOESNT_EXIST("-4", "请求的资源不存在"), OPERATION_FREQUENTLY("-5", "请求频繁,请勿重复请求"), REQUEST_COUNT_LIMIT("10000", "访问次数超出限制"), SUCCESS("0", "请求成功"), MISSING_SYSTEM_PARAMETERS("6", "缺少系统参数"), APP_KEY_NOT_EXIST("7", "app_key不存在或合作方不合作"), API_VERSION_NOT_SUPPORT("8", "api版本号不支持"), PARAM_SIGN_FAILED("9", "参数验证失败"); private ErrorCodeEnum(String errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } private String errorCode; private String errorMsg; public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } }