通用异常处理总结
一:创建通用处理异常
package com.example.demo01.utils;
public class CommonException extends RuntimeException {
private final String errorCode;
private final String errorMessage;
public CommonException(String errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public CommonException(String errorCode, String errorMessage, Throwable throwable) {
super(throwable);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
@Override
public boolean equals(final Object o) {
if (o == this) {
return true;
} else if (!(o instanceof CommonException)) {
return false;
} else {
CommonException other = (CommonException) o;
if (!other.canEqual(this)) {
return false;
} else if (!super.equals(o)) {
return false;
} else {
if (this.getErrorCode() == null) {
if (other.getErrorCode() != null) {
return false;
}
} else if (!this.getErrorCode().equals(other.getErrorCode())) {
return false;
}
if (this.getErrorMessage() == null) {
if (other.getErrorMessage() != null) {
return false;
}
} else if (!this.getErrorMessage().equals(other.getErrorMessage())) {
return false;
}
return true;
}
}
}
protected boolean canEqual(final Object other) {
return other instanceof CommonException;
}
@Override
public int hashCode() {
boolean prime = true;
int result = super.hashCode();
result = result * 59 + (this.getErrorCode() == null ? 43 : this.getErrorCode().hashCode());
result = result * 59 + (this.getErrorMessage() == null ? 43 : this.getErrorMessage().hashCode());
return result;
}
public String getErrorCode() {
return this.errorCode;
}
public String getErrorMessage() {
return this.errorMessage;
}
@Override
public String toString() {
return "CommonException(errorCode=" + this.getErrorCode() + ", errorMessage=" + this.getErrorMessage() + ")";
}
}
二:通用请求异常处理
package com.example.demo01.utils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
import java.util.Objects;
public class GlobalExceptionAdvice {
public GlobalExceptionAdvice() {
}
@ExceptionHandler({CommonException.class})
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Result ftbExceptionHandler(CommonException exception) {
return ResultUtils.fail(exception.getErrorCode(), exception.getErrorMessage());
}
@ExceptionHandler({RuntimeException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Result runtimeExceptionHandler(RuntimeException exception) {
exception.printStackTrace();
return ResultUtils.fail(exception.getMessage());
}
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Result httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException exception) {
exception.printStackTrace();
return ResultUtils.fail(exception.getMessage());
}
@ExceptionHandler({ConstraintViolationException.class})
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result constraintViolationExceptionHandler(ConstraintViolationException exception) {
exception.printStackTrace();
return ResultUtils.fail(exception.getMessage());
}
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Result methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException exception) {
exception.printStackTrace();
return ResultUtils.fail(exception.getMessage());
}
@ExceptionHandler({DuplicateKeyException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Result duplicateKeyExceptionHandler(DuplicateKeyException exception) {
exception.printStackTrace();
return ResultUtils.fail(exception.getMessage());
}
@ExceptionHandler({MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
exception.printStackTrace();
String message = "传入参数异常";
BindingResult result = exception.getBindingResult();
if (Objects.nonNull(result) && result.hasErrors()) {
Iterator var4 = result.getAllErrors().iterator();
if (var4.hasNext()) {
ObjectError error = (ObjectError) var4.next();
message = error.getDefaultMessage();
}
}
return ResultUtils.fail(message);
}
}
三:通用异常处理
package com.example.demo01.utils;
import com.example.demo01.enums.ErrorExceptionEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;
@Slf4j
@ControllerAdvice
@RestControllerAdvice
public class ExceptionAdvice extends GlobalExceptionAdvice {
@ExceptionHandler({Exception.class})
@ResponseBody
public Result<String> exceptionHandler(Exception exception) {
log.error("#exceptionHandler", exception);
return ResultUtils.fail(exception.getMessage());
}
@ExceptionHandler({Throwable.class})
@ResponseBody
public Result<String> handleExceptionGlobal(Throwable ex) {
Result<String> result = ResultUtils
.fail(ErrorExceptionEnums.SERVICE_INTERNAL_ERROR.getErrorCode(), ex.getMessage());
log.error("#handleExceptionGlobal ====> result:{}", result, ex);
return result;
}
@ExceptionHandler(BindException.class)
@ResponseBody
public Result<Object> bindExceptionHandler(BindException ex) {
String message = ex.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(
Collectors.joining());
Result<Object> result = ResultUtils
.fail(ErrorExceptionEnums.SERVICE_INTERNAL_ERROR.getErrorCode(), message);
log.error("#bindExceptionHandler ====> result:{}", result, ex);
return result;
}
@Override
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Result<Object> constraintViolationExceptionHandler(ConstraintViolationException ex) {
String message = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage)
.collect(Collectors.joining());
String messageResult = message;
Result<Object> result = ResultUtils
.fail(ErrorExceptionEnums.SERVICE_INTERNAL_ERROR.getErrorCode(), messageResult);
log.error("#constraintViolationExceptionHandler ====> result:{}", result, ex);
return result;
}
@Override
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Result<Object> methodArgumentNotValidExceptionHandler(
MethodArgumentNotValidException ex) {
String message = ex.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
Result<Object> result = ResultUtils
.fail(ErrorExceptionEnums.SERVICE_INTERNAL_ERROR.getErrorCode(), message);
log.error("#methodArgumentNotValidExceptionHandler ====> result:{}", result, ex);
return result;
}
private String deleteSameString(String str) {
StringBuilder stringBuffer = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (str.indexOf(str.charAt(i)) == i) {
stringBuffer.append(str.charAt(i));
}
}
return stringBuffer.toString();
}
}
&所需依赖的公共类
result
package com.example.demo01.utils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.UUID;
@ApiModel("API统一返回数据封装类")
@JsonIgnoreProperties(
ignoreUnknown = true
)
public class Result<T> implements Serializable {
public static final String SUCCEED = " SUCCEED ";
public static final String FAILED = " FAILED ";
@ApiModelProperty("返回状态:SUCCEED和FAILED")
private String returnStatus;
@ApiModelProperty("时间戳")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Long serverTime;
@ApiModelProperty("请求ID")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String requestId;
@ApiModelProperty("错误码")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String errorCode;
@ApiModelProperty("错误信息")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String errorMessage;
@ApiModelProperty("错误扩展信息")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Object extMessage;
@ApiModelProperty("封装数据")
@JsonInclude(JsonInclude.Include.NON_NULL)
private T data;
public static <T> Result<T> fail(String errCode, String errMsg) {
Result<T> result = buildBasic("FAILED");
result.setErrorCode(errCode);
result.setErrorMessage(errMsg);
return result;
}
public static <T> Result<T> success(T data) {
Result<T> result = success();
result.setData(data);
return result;
}
public static <T> Result<T> success() {
Result<T> result = buildBasic("SUCCEED");
return result;
}
private static <T> Result<T> buildBasic(String status) {
Result<T> result = new Result();
result.setReturnStatus(status);
result.setServerTime(System.currentTimeMillis());
result.setRequestId(createRequestId());
return result;
}
protected static String createRequestId() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public String getReturnStatus() {
return this.returnStatus;
}
public Long getServerTime() {
return this.serverTime;
}
public String getRequestId() {
return this.requestId;
}
public String getErrorCode() {
return this.errorCode;
}
public String getErrorMessage() {
return this.errorMessage;
}
public Object getExtMessage() {
return this.extMessage;
}
public T getData() {
return this.data;
}
public void setReturnStatus(final String returnStatus) {
this.returnStatus = returnStatus;
}
public void setServerTime(final Long serverTime) {
this.serverTime = serverTime;
}
public void setRequestId(final String requestId) {
this.requestId = requestId;
}
public void setErrorCode(final String errorCode) {
this.errorCode = errorCode;
}
public void setErrorMessage(final String errorMessage) {
this.errorMessage = errorMessage;
}
public void setExtMessage(final Object extMessage) {
this.extMessage = extMessage;
}
public void setData(final T data) {
this.data = data;
}
@Override
public boolean equals(final Object object) {
if (object == this) {
return true;
} else if (!(object instanceof Result)) {
return false;
} else {
Result<?> other = (Result) object;
if (!other.canEqual(this)) {
return false;
} else {
label95: {
if (this.getServerTime() == null) {
if (other.getServerTime() == null) {
break label95;
}
} else if (this.getServerTime().equals(other.getServerTime())) {
break label95;
}
return false;
}
if (this.getReturnStatus() == null) {
if (other.getReturnStatus() != null) {
return false;
}
} else if (!this.getReturnStatus().equals(other.getReturnStatus())) {
return false;
}
if (this.getRequestId() == null) {
if (other.getRequestId() != null) {
return false;
}
} else if (!this.getRequestId().equals(other.getRequestId())) {
return false;
}
label74: {
if (this.getErrorCode() == null) {
if (other.getErrorCode() == null) {
break label74;
}
} else if (this.getErrorCode().equals(other.getErrorCode())) {
break label74;
}
return false;
}
label67: {
if (this.getErrorMessage() == null) {
if (other.getErrorMessage() == null) {
break label67;
}
} else if (this.getErrorMessage().equals(other.getErrorMessage())) {
break label67;
}
return false;
}
if (this.getExtMessage() == null) {
if (other.getExtMessage() != null) {
return false;
}
} else if (!this.getExtMessage().equals(other.getExtMessage())) {
return false;
}
if (this.getData() == null) {
if (other.getData() != null) {
return false;
}
} else if (!this.getData().equals(other.getData())) {
return false;
}
return true;
}
}
}
protected boolean canEqual(final Object other) {
return other instanceof Result;
}
@Override
public int hashCode() {
int result = 59 + (this.getServerTime() == null ? 43 : this.getServerTime().hashCode());
result = result * 59 + (this.getReturnStatus() == null ? 43 : this.getReturnStatus().hashCode());
result = result * 59 + (this.getRequestId() == null ? 43 : this.getRequestId().hashCode());
result = result * 59 + (this.getErrorCode() == null ? 43 : this.getErrorCode().hashCode());
result = result * 59 + (this.getErrorMessage() == null ? 43 : this.getErrorMessage().hashCode());
result = result * 59 + (this.getExtMessage() == null ? 43 : this.getExtMessage().hashCode());
result = result * 59 + (this.getData() == null ? 43 : this.getData().hashCode());
return result;
}
@Override
public String toString() {
return "Result(returnStatus=" + this.getReturnStatus() + ", serverTime=" + this.getServerTime() + ", requestId=" + this.getRequestId() + ", errorCode=" + this.getErrorCode() + ", errorMessage=" + this.getErrorMessage() + ", extMessage=" + this.getExtMessage() + ", data=" + this.getData() + ")";
}
public Result() {
}
}
resultUtils
package com.example.demo01.utils;
import java.util.Objects;
public final class ResultUtils {
private ResultUtils() {
}
public static <T> Result<T> success() {
return Result.success();
}
public static <T> Result<T> success(T data) {
return Result.success(data);
}
public static <T> PageResult<T> success(T data, Integer totalCount) {
return PageResult.success(data, totalCount, (Integer) null, (Integer) null);
}
public static <T> PageResult<T> success(T data, Integer totalCount, Integer pageNo, Integer pageSize) {
return PageResult.success(data, totalCount, pageNo, pageSize);
}
public static <T> Result<T> fail(IError error) {
return fail(error.getErrorCode(), error.getErrorMessage());
}
public static <T> Result<T> fail(String errorMessage) {
return fail("", errorMessage);
}
public static <T> Result<T> fail(IError error, Object extMessage) {
Result result = fail(error.getErrorCode(), error.getErrorMessage());
result.setExtMessage(extMessage);
return result;
}
public static <T> Result<T> fail(String errorCode, String errorMessage) {
return Result.fail(errorCode, errorMessage);
}
public static void checkResult(Result result, IError errorCodeEnum) {
if (Objects.isNull(result)) {
throw ExceptionUtils.getException(errorCodeEnum);
} else if (isFailed(result)) {
throw ExceptionUtils.getException(errorCodeEnum.getErrorCode(), errorCodeEnum.getErrorMessage() + result.getErrorMessage());
}
}
public static boolean isSuccess(Result result) {
return "SUCCEED".equals(result.getReturnStatus());
}
public static boolean isFailed(Result result) {
return "FAILED".equals(result.getReturnStatus());
}
}
pageResult
package com.example.demo01.utils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("带分页的响应体封装类")
@JsonIgnoreProperties(
ignoreUnknown = true
)
public class PageResult<T> extends Result<T> {
@ApiModelProperty("总共条数")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer totalCount;
@ApiModelProperty("页数")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer pageNo;
@ApiModelProperty("本页条数")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Integer pageSize;
public static <T> PageResult<T> success(T data, Integer totalCount, Integer pageNo, Integer pageSize) {
PageResult<T> result = buildBasic("SUCCEED");
result.setData(data);
result.setTotalCount(totalCount);
result.setPageNo(pageNo);
result.setPageSize(pageSize);
return result;
}
private static <T> PageResult<T> buildBasic(String status) {
PageResult<T> result = new PageResult();
result.setReturnStatus(status);
result.setServerTime(System.currentTimeMillis());
result.setRequestId(createRequestId());
return result;
}
public Integer getTotalCount() {
return this.totalCount;
}
public Integer getPageNo() {
return this.pageNo;
}
public Integer getPageSize() {
return this.pageSize;
}
public void setTotalCount(final Integer totalCount) {
this.totalCount = totalCount;
}
public void setPageNo(final Integer pageNo) {
this.pageNo = pageNo;
}
public void setPageSize(final Integer pageSize) {
this.pageSize = pageSize;
}
@Override
public boolean equals(final Object object) {
if (object == this) {
return true;
} else if (!(object instanceof PageResult)) {
return false;
} else {
PageResult<?> other = (PageResult) object;
if (!other.canEqual(this)) {
return false;
} else {
label47: {
if (this.getTotalCount() == null) {
if (other.getTotalCount() == null) {
break label47;
}
} else if (this.getTotalCount().equals(other.getTotalCount())) {
break label47;
}
return false;
}
if (this.getPageNo() == null) {
if (other.getPageNo() != null) {
return false;
}
} else if (!this.getPageNo().equals(other.getPageNo())) {
return false;
}
if (this.getPageSize() == null) {
if (other.getPageSize() != null) {
return false;
}
} else if (!this.getPageSize().equals(other.getPageSize())) {
return false;
}
return true;
}
}
}
@Override
protected boolean canEqual(final Object other) {
return other instanceof PageResult;
}
@Override
public int hashCode() {
int result = 59 + (this.getTotalCount() == null ? 43 : this.getTotalCount().hashCode());
result = result * 59 + (this.getPageNo() == null ? 43 : this.getPageNo().hashCode());
result = result * 59 + (this.getPageSize() == null ? 43 : this.getPageSize().hashCode());
return result;
}
@Override
public String toString() {
return "PageResult(totalCount=" + this.getTotalCount() + ", pageNo=" + this.getPageNo() + ", pageSize=" + this.getPageSize() + ")";
}
public PageResult() {
}
}
errorExceptionEnums
package com.example.demo01.enums;
import com.example.demo01.utils.IError;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ErrorExceptionEnums implements IError {
SERVICE_INTERNAL_ERROR("000001", "服务内部错误");
private final String errorCode;
private final String errorMessage;
}
ierror