import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
/**
* The class Wrapper.
*
* @param the type parameter @author [email protected]
*/
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Wrapper implements Serializable {
/**
* 序列化标识
*/
private static final long serialVersionUID = 4893280118017319089L;
/**
* 成功码.
*/
public static final int SUCCESS_CODE = 200;
/**
* 成功信息.
*/
public static final String SUCCESS_MESSAGE = "操作成功";
/**
* 错误码.
*/
public static final int ERROR_CODE = 500;
/**
* 错误信息.
*/
public static final String ERROR_MESSAGE = "内部异常";
/**
* 错误码:参数非法
*/
public static final int ILLEGAL_ARGUMENT_CODE_ = 100;
/**
* 错误信息:参数非法
*/
public static final String ILLEGAL_ARGUMENT_MESSAGE = "参数非法";
/**
* 编号.
*/
@ApiModelProperty(value = "编号 ")
private int code;
/**
* 信息.
*/
@ApiModelProperty(value = "信息 ")
private String message;
/**
* 结果数据
*/
@ApiModelProperty(value = "结果数据 ")
private T result;
/**
* Instantiates a new wrapper. default code=200
*/
Wrapper() {
this(SUCCESS_CODE, SUCCESS_MESSAGE);
}
/**
* Instantiates a new wrapper.
*
* @param code the code
* @param message the message
*/
Wrapper(int code, String message) {
this(code, message, null);
}
/**
* Instantiates a new wrapper.
*
* @param code the code
* @param message the message
* @param result the result
*/
Wrapper(int code, String message, T result) {
super();
this.code(code).message(message).result(result);
}
/**
* Sets the 编号 , 返回自身的引用.
*
* @param code the new 编号
*
* @return the wrapper
*/
private Wrapper code(int code) {
this.setCode(code);
return this;
}
/**
* Sets the 信息 , 返回自身的引用.
*
* @param message the new 信息
*
* @return the wrapper
*/
private Wrapper message(String message) {
this.setMessage(message);
return this;
}
/**
* Sets the 结果数据 , 返回自身的引用.
*
* @param result the new 结果数据
*
* @return the wrapper
*/
public Wrapper result(T result) {
this.setResult(result);
return this;
}
/**
* 判断是否成功: 依据 Wrapper.SUCCESS_CODE == this.code
*
* @return code =200,true;否则 false.
*/
@JsonIgnore
public boolean success() {
return Wrapper.SUCCESS_CODE == this.code;
}
/**
* 判断是否成功: 依据 Wrapper.SUCCESS_CODE != this.code
*
* @return code !=200,true;否则 false.
*/
@JsonIgnore
public boolean error() {
return !success();
}
}
import org.apache.commons.lang3.StringUtils;
/**
* The class Wrap mapper.
*
*@author jiangjunwei
*/
public class WrapMapper {
/**
* Instantiates a new wrap mapper.
*/
private WrapMapper() {
}
/**
* Wrap.
*
* @param the element type
* @param code the code
* @param message the message
* @param o the o
*
* @return the wrapper
*/
public static Wrapper wrap(int code, String message, E o) {
return new Wrapper<>(code, message, o);
}
/**
* Wrap.
*
* @param the element type
* @param code the code
* @param message the message
*
* @return the wrapper
*/
public static Wrapper wrap(int code, String message) {
return wrap(code, message, null);
}
/**
* Wrap.
*
* @param the element type
* @param code the code
*
* @return the wrapper
*/
public static Wrapper wrap(int code) {
return wrap(code, null);
}
/**
* Wrap.
*
* @param the element type
* @param e the e
*
* @return the wrapper
*/
public static Wrapper wrap(Exception e) {
return new Wrapper<>(Wrapper.ERROR_CODE, e.getMessage());
}
/**
* Un wrapper.
*
* @param the element type
* @param wrapper the wrapper
*
* @return the e
*/
public static E unWrap(Wrapper wrapper) {
return wrapper.getResult();
}
/**
* Wrap ERROR. code=100
*
* @param the element type
*
* @return the wrapper
*/
public static Wrapper illegalArgument() {
return wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, Wrapper.ILLEGAL_ARGUMENT_MESSAGE);
}
/**
* Wrap ERROR. code=500
*
* @param the element type
*
* @return the wrapper
*/
public static Wrapper error() {
return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE);
}
/**
* Error wrapper.
*
* @param the type parameter
* @param message the message
*
* @return the wrapper
*/
public static Wrapper error(String message) {
return wrap(Wrapper.ERROR_CODE, StringUtils.isBlank(message) ? Wrapper.ERROR_MESSAGE : message);
}
/**
* Wrap SUCCESS. code=200
*
* @param the element type
*
* @return the wrapper
*/
public static Wrapper ok() {
return new Wrapper<>();
}
/**
* Ok wrapper.
*
* @param the type parameter
* @param o the o
*
* @return the wrapper
*/
public static Wrapper ok(E o) {
return new Wrapper<>(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, o);
}
}
@Data
public class BusinessException extends RuntimeException {
private Integer code;
public BusinessException(Integer code, String msg) {
super(msg);
this.code = code;
}
}
import com.paascloud.provider.exception.CustomException;
import com.paascloud.wrapper.WrapMapper;
import com.paascloud.wrapper.Wrapper;
import feign.RetryableException;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* @author 颜兵
* @version 1.00
* @Date in 9:24 2020/5/27
* 全局异常处理 无法处理filter抛出的异常
*/
@Slf4j
@Component
@ControllerAdvice
public class GlobalException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
/**
* @Description TODO
* @Auther luojiawen
* @Date 2020/5/22 16:07
* @Version 1.0
**/
@ExceptionHandler(CustomException.class)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public Map handleCustomException(CustomException e) throws Exception {
Map error = new HashMap<>();
error.put("code", e.getCode());
error.put("message", e.getMessage());
return error;
}
/**
* 运行时异常 一般业务错误
*
* @param request
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Wrapper businessException(HttpServletRequest request, BusinessException e) {
return WrapMapper.wrap(e.getCode(), e.getMessage());
}
@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Wrapper duplicateKeyException(HttpServletRequest request, DuplicateKeyException ex) {
log.error("异常:", ex);
return WrapMapper.wrap(ErrorsCode.PRIMARY_KEY_CONFLICT.getCode(), ErrorsCode.PRIMARY_KEY_CONFLICT.getMsg());
}
/**
* 方法参数校验异常 Validate
*
* @param request
* @param ex
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Wrapper handleValidationException(HttpServletRequest request, ConstraintViolationException ex) {
log.error("异常:" + request.getRequestURI(), ex);
String collect = ex.getConstraintViolations().stream().filter(Objects::nonNull)
.map(cv -> cv == null ? "null" : cv.getPropertyPath() + ": " + cv.getMessage())
.collect(Collectors.joining(", "));
log.info("请求参数异常", collect);
return WrapMapper.wrap(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}
/**
* Bean 校验异常 Validate
*
* @param request
* @param exception
* @return
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class) //400
@ResponseBody
public Wrapper methodArgumentValidationHandler(HttpServletRequest request, MethodArgumentNotValidException exception) {
log.info("异常:" + request.getRequestURI(), exception);
log.info("请求参数错误!{}", getExceptionDetail(exception), "参数数据:" + showParams(request));
String msg = "";
if (exception.getBindingResult() != null && !CollectionUtils.isEmpty(exception.getBindingResult().getAllErrors())) {
msg = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
} else {
msg = exception.getMessage();
}
return WrapMapper.wrap(HttpStatus.BAD_REQUEST.value(), msg);
}
/**
* 绑定异常
*
* @param request
* @param pe
* @return
*/
@ExceptionHandler(BindException.class)
@ResponseBody
public Wrapper bindException(HttpServletRequest request, BindException pe) {
log.error("异常:" + request.getRequestURI(), pe);
Map map = new HashMap();
if (pe.getBindingResult() != null) {
List allErrors = pe.getBindingResult().getAllErrors();
allErrors.stream().filter(Objects::nonNull).forEach(objectError -> {
map.put("请求路径:" + request.getRequestURI() + "--请求参数:" + (((FieldError) ((FieldError) allErrors.get(0))).getField().toString()), objectError.getDefaultMessage());
});
}
return WrapMapper.wrap(HttpStatus.BAD_REQUEST.value(), "请求参数绑定失败", map);
}
/**
* 访问接口参数不全
*
* @param request
* @param pe
* @return
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseBody
public Wrapper missingServletRequestParameterException(HttpServletRequest request, MissingServletRequestParameterException pe) {
log.error("异常:" + request.getRequestURI(), pe);
return WrapMapper.wrap(HttpStatus.BAD_REQUEST.value(), "该请求路径:" + request.getRequestURI() + "下的请求参数不全:" + pe.getMessage());
}
/**
* HttpRequestMethodNotSupportedException
*
* @param request
* @param pe
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
public Wrapper httpRequestMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException pe) {
log.error("异常:" + request.getRequestURI(), pe);
return WrapMapper.wrap(HttpStatus.BAD_REQUEST.value(), "请求方式不正确");
}
/**
* 其他异常
*
* @param request
* @param pe
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Wrapper otherException(HttpServletRequest request, Exception pe) {
log.error("异常:" + request.getRequestURI(), pe);
return WrapMapper.wrap(HttpStatus.BAD_REQUEST.value(), getExceptionDetail(pe));
}
/**
* fegin 异常
*
* @return
*/
@ExceptionHandler(value = {RetryableException.class})
@ResponseBody
public Wrapper retryableExceptionHandler(HttpServletRequest request, RetryableException ex) {
log.error("异常:" + request.getRequestURI(), ex);
return WrapMapper.wrap(Wrapper.ERROR_CODE, "fegin调用异常:" + ex.getMessage());
}
/**
* 异常详情
*
* @param e
* @return
*/
private String getExceptionDetail(Exception e) {
log.error("异常:", e);
StringBuilder stringBuffer = new StringBuilder(e.toString() + "\n");
StackTraceElement[] messages = e.getStackTrace();
Arrays.stream(messages).filter(Objects::nonNull).forEach(stackTraceElement -> {
stringBuffer.append(stackTraceElement.toString() + "\n");
});
return stringBuffer.toString();
}
/**
* 请求参数
*
* @param request
* @return
*/
public String showParams(HttpServletRequest request) {
Map map = new HashMap();
StringBuilder stringBuilder = new StringBuilder();
Enumeration paramNames = request.getParameterNames();
stringBuilder.append("----------------参数开始-------------------");
stringBuilder.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
if (Objects.nonNull(paramNames)) {
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length > 0) {
String paramValue = paramValues[0];
if (paramValue.length() != 0) {
stringBuilder.append("参数名:").append(paramName).append("参数值:").append(paramValue);
}
}
}
}
stringBuilder.append("----------------参数结束-------------------");
return stringBuilder.toString();
}
/**
* 数据类型转换异常
*
* @return
*/
// @ExceptionHandler(value = {ClassCastException.class})
// @ResponseBody
// public Wrapper classCastExceptionHandler(ClassCastException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,对象类型转换出错" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,对象类型转换出错");
// }
/**
* IO异常
*
* @return
*/
@ExceptionHandler(value = {IOException.class})
@ResponseBody
public Wrapper iOExceptionHandler(IOException ex) {
log.info("系统异常,IO异常" + ex.getMessage());
return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,IO异常");
}
/**
* 数组越界异常
*
* @return
*/
// @ExceptionHandler(value = {IndexOutOfBoundsException.class})
// @ResponseBody
// public Wrapper indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统出错,数组越界异常" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统出错,数组越界异常");
// }
/**
* 类型不匹配异常
*
* @return
*/
// @ExceptionHandler(value = {TypeMismatchException.class})
// @ResponseBody
// public Wrapper requestTypeMismatchExceptionHandler(TypeMismatchException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,类型不匹配出错" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,类型不匹配出错");
// }
/**
* 运行时异常
*
* @return
*/
// @ExceptionHandler(value = {MissingServletRequestParameterException.class})
// @ResponseBody
// public Wrapper requestMissingServletRequest(MissingServletRequestParameterException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("[服务器]类型不匹配异常" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "[服务器]类型不匹配异常");
// }
/**
* 不允许的方法异常
*
* @return
*/
// @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
// @ResponseBody
// public Wrapper httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,不允许的方法错误" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,不允许的方法错误");
// }
/**
* 请求媒体类型和响应媒体类型未一致异常
*
* @return
*/
// @ExceptionHandler(value = {HttpMediaTypeNotAcceptableException.class})
// @ResponseBody
// public Wrapper httpMediaTypeNotAcceptableExceptionHandler(HttpMediaTypeNotAcceptableException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,请求媒体类型和响应媒体类型未一致错误" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,请求媒体类型和响应媒体类型未一致错误");
// }
/**
* 内部错误异常
*
* @return
*/
// @ExceptionHandler(value = {ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
// @ResponseBody
// public Wrapper conversionNotSupportedExceptionHandler(Exception ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,内部错误" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,内部错误");
// }
/**
* 数据格式转换出错
*
* @return
*/
// @ExceptionHandler(value = {NumberFormatException.class})
// @ResponseBody
// public Wrapper numberFormatExceptionHandler(NumberFormatException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,数据格式转换出错" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,数据格式转换出错");
// }
/**
* 请求参数异常
*
* @return
*/
@ExceptionHandler(value = {HttpMessageNotReadableException.class})
@ResponseBody
public Wrapper requestNotReadableExceptionHandler(HttpMessageNotReadableException ex) {
log.error("异常:", ex);
return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, Wrapper.ILLEGAL_ARGUMENT_MESSAGE);
}
/**
* 当出现空指针异常的时候处理
*
* @return
*/
//@ExceptionHandler(value = {NullPointerException.class})
@ResponseBody
public Wrapper resovlerNullPointerException(NullPointerException ex) {
log.info("系统异常,空指针异常" + ex);
return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,空指针异常");
}
/**
* 运行时异常
*
* @return
*/
//@ExceptionHandler(value = {RuntimeException.class})
@ResponseBody
public Wrapper runtimeExceptionHandler(RuntimeException ex) {
log.info("系统异常,请联系管理员" + ex);
return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,请联系管理员");
}
/**
* 未知方法异常
*
* @return
*/
// @ExceptionHandler(value = {NoSuchMethodException.class})
// @ResponseBody
// public Wrapper noSuchMethodExceptionHandler(NoSuchMethodException ex) {
// ex.printStackTrace(new PrintStream(baos));
// String exception = baos.toString();
// log.info("系统异常,未知方法异常" + exception);
// return WrapMapper.wrap(Wrapper.ERROR_CODE, "系统异常,未知方法异常");
// }
}
throw new BusinessException(Wrapper.ERROR_CODE, "*******");