前言
如题,部分代码来自百度
代码
package com.xiben.pm.file.system.init.exception;
import com.xiben.pm.file.system.dto.RestCode;
import lombok.Data;
/**
* @author :qilong sun
* @date :Created in 2020/4/7 12:58
* @description:自定义异常 ps:spring 对于 RuntimeException 异常才会进行事务回滚。
* @modified By:
* @version: V1.0$
*/
@Data
public class MyException extends RuntimeException {
/**
* 编码
*/
private Integer code = RestCode.FAILURE.getCode();
/**
* 描述
*/
private String msg = RestCode.FAILURE.getMsg();
public MyException(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public MyException(String msg) {
this.msg = msg;
}
}
package com.xiben.pm.file.system.init.exception;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.xiben.pm.file.system.dto.RestCode;
import com.xiben.pm.file.system.dto.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
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.servlet.NoHandlerFoundException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 全局异常处理器
* https://blog.csdn.net/jinjiankang/article/details/89711493
*
* @author qilong.sun
*/
@ControllerAdvice
@Slf4j
public class GlobalDefaultExceptionHandler {
/**
* 用来处理bean validation异常
* @param ex
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public RestResponse resolveConstraintViolationException(ConstraintViolationException ex){
RestResponse failure = RestResponse.failure();
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
if(!CollectionUtils.isEmpty(constraintViolations)){
StringBuilder msgBuilder = new StringBuilder();
for(ConstraintViolation constraintViolation :constraintViolations){
msgBuilder.append(constraintViolation.getMessage()).append(",");
}
String errorMessage = msgBuilder.toString();
if(errorMessage.length()>1){
errorMessage = errorMessage.substring(0,errorMessage.length()-1);
}
failure.setMsg(errorMessage);
return failure;
}
failure.setMsg(ex.getMessage());
return failure;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public RestResponse resolveMethodArgumentNotValidException(MethodArgumentNotValidException ex){
RestResponse failure = RestResponse.failure();
List<ObjectError> objectErrors = ex.getBindingResult().getAllErrors();
if(!CollectionUtils.isEmpty(objectErrors)) {
StringBuilder msgBuilder = new StringBuilder();
for (ObjectError objectError : objectErrors) {
msgBuilder.append(objectError.getDefaultMessage()).append(",");
}
String errorMessage = msgBuilder.toString();
if (errorMessage.length() > 1) {
errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
}
failure.setMsg(errorMessage);
return failure;
}
failure.setMsg(ex.getMessage());
return failure;
}
/**
* 拦截捕捉自定义异常 MyException.class
*
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = MyException.class)
public Map myErrorHandler(MyException ex) {
Map map = new HashMap();
map.put("code", ex.getCode());
map.put("msg", ex.getMsg());
return map;
}
/**
* 处理 Exception 类型的异常
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public RestResponse defaultExceptionHandler(Exception e) {
log.error(e.getMessage());
String errmsg;
if (e instanceof NoHandlerFoundException) {
return RestResponse.failure(RestCode.NOT_FOUND);
} else if(e instanceof InvalidFormatException) {
return RestResponse.failure(RestCode.ERROR);
} else {
errmsg = RestCode.ERROR.getMsg();
}
RestResponse restResponse = new RestResponse();
restResponse.setMsg(errmsg);
restResponse.setCode(RestCode.FAILURE.getCode());
return restResponse;
}
}
/**
* @author :sunqilong
* @date :Created in 2019/12/29 13:35
* @description:返回的code以及返回的message
* @modified By:
* @version: $1.0
*/
public enum RestCode {
SUCCESS(200, "响应成功"),
FAILURE(401, "响应失败"),
NOT_FOUND(404, "没有找到请求的路径"),
ERROR(500, "服务器异常"),
NOT_LOGINED(302, "未登录,请登录后访问"),
UNKNOW_ERROR(500, "未知错误");
RestCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int code;
public String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
/**
* @author :sunqilong
* @date :Created in 2019/12/29 13:35
* @description:统一API响应结果封装
* @modified By:
* @version: $1.0
*/
public class RestResponse<T> {
private int code;
private String msg;
private T data;
public RestResponse() {
this(RestCode.SUCCESS.getCode(), RestCode.SUCCESS.getMsg());
}
public RestResponse(int code, String msg) {
this.code = code;
this.msg = msg;
}
public RestResponse(T data) {
this(RestCode.SUCCESS.getCode(), RestCode.SUCCESS.getMsg(), data);
}
public RestResponse(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static RestResponse success() {
return new RestResponse<>();
}
public static <T> RestResponse<T> success(T data) {
RestResponse restResponse = new RestResponse();
restResponse.setData(data);
return restResponse;
}
public static RestResponse failure() {
RestResponse restResponse = new RestResponse<>(RestCode.FAILURE.getCode(), RestCode.FAILURE.getMsg());
return restResponse;
}
public static RestResponse failure(String msg) {
RestResponse restResponse = new RestResponse();
restResponse.setCode(RestCode.FAILURE.getCode());
restResponse.setMsg(msg);
return restResponse;
}
public static RestResponse failure(RestCode restCode) {
RestResponse restResponse = new RestResponse();
restResponse.setCode(restCode.getCode());
restResponse.setMsg(restCode.getMsg());
return restResponse;
}
public int getCode() {
return code;
}
public RestResponse setCode(int code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public RestResponse setMsg(String msg) {
this.msg = msg;
return this;
}
public T getData() {
return data;
}
public RestResponse setData(T data) {
this.data = data;
return this;
}