JavaWeb项目统一处理
springboot项目下的一些统一操作。
idea需要实现安装lombok插件
依赖:
依赖少了的,漏了的自己引。
<!--切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!--fastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.16.20</version>
</dependency>
<!--jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</dependency>
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
自定义异常类:
import lombok.extern.slf4j.Slf4j;
/**
* @author Administrator
* @version 1.0.0
* @date 2019:06:20 10:57
*/
@Slf4j
public class BusinessException extends Exception {
private String throwable;
private static final long serialVersionUID = 1L;
public BusinessException() {
super();
}
public BusinessException(String message) {
super(message);
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(String message, String throwable) {
super(message);
this.throwable = throwable;
log.info("=====" + throwable);
}
public String getThrowable() {
return throwable;
}
}
响应结果枚举:
/**
* 响应枚举
*
* @author Administrator
* @version 1.0.0
* @date 2019/8/14 11:33
*/
public enum ResponseResultEnum {
/**
* 枚举
*/
SUCCESS(200, "SUCCESS"),
AUTH_ERROR(403, "权限不足"),
SERVER_ERROR(500, "服务器异常"),
PARAMS_ERROR(400, "参数错误"),
JSON_PARSE_ERROR(155, "Json解析错误"),
ILLEAGAL_STRING(165, "非法字符串"),
SHIRO_AUTH_ERROR(999, "无效的token"),
USER_TOKEN_INVALID(401, "用户身份已失效"),
UNKNOW_ERROR(900, "未知错误");
private int code;
private String msg;
ResponseResultEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
状态枚举:
/**
* @author Administrator
* @date 2019:08:26 17:46
*/
public enum StatusEnum {
/**
* 业务响应枚举
*/
NORMAL(1, 10000, "NORMAL", "正常"),
INVALID(2, 10001, "INVALID", "无效"),
LOCK(3, 10002, "LOCK", "已锁定"),
NO_ACTIVE(4, 10003, "DISABLED", "未激活"),
NOCONFIG(5, 10004, "NOCONFIG", "未配置"),
RUNNING(6, 10005, "RUNNING", "运行中"),
STOPPED(7, 10006, "STOPPED", "已停止"),
CONFIGURED(8, 10007, "CONFIGURED", "已配置"),
ACTIVATED(9, 10008, "ACTIVATED", "已激活"),
PENDING(10, 10009, "PENDING", "待审批"),
BOOTFAILED(11, 10010, "BOOTFAILED", "启动失败"),
NOINSTALL(12, 10011, "NOINSTALL", "未安装"),
NOINSTANTIATION(13, 10012, "NOINSTANTIATION", "未实例化"),
CONFIGURING(14, 10013, "CONFIGURING", "配置中"),
AGREED(15, 100014, "AGREED", "已同意"),
BUILDING_CONTAINER(16, 100015, "BUILDING", "正在构建容器"),
RUNNING_CONTAINER(17, 100016, "RUNNING_CONTAINER", "正在运行容器"),
ACTIVATING(18, 100017, "ACTIVATING", "激活中"),
INSTALLING(19, 100018, "INSTALLING", "正在安装"),
INSTANTIATING(20, 100019, "INSTANTIATING", "正在实例化"),
UPGRADING(21, 100020, "UPGRADING", "正在升级");
private int id;
private int code;
private String enName;
private String zhName;
StatusEnum(int id, int code, String enName, String zhName) {
this.id = id;
this.code = code;
this.enName = enName;
this.zhName = zhName;
}
public int getId() {
return id;
}
public int getCode() {
return code;
}
public String getZhName() {
return zhName;
}
public String getEnName() {
return enName;
}
}
统一返回
统一响应格式:
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.thyc.fabric.common.enumeration.ResponseResultEnum;
import com.thyc.fabric.common.enumeration.StatusEnum;
import com.thyc.fabric.common.exception.BusinessException;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import java.math.BigDecimal;
/**
* api统一返回结果类
*
* @author wzm
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResult<T> {
private int code;
private String message;
private T data;
public ApiResult() {
}
public ApiResult(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static <T> ApiResult valueOf(String msg, T body) {
ApiResult<T> apiResult = new ApiResult<>();
apiResult.setCode(ResponseResultEnum.SUCCESS.getCode());
apiResult.setMessage(msg);
apiResult.setData(body);
return apiResult;
}
public static <T> ApiResult valueOf(T body) {
ApiResult<T> apiResult = new ApiResult<>();
apiResult.setCode(ResponseResultEnum.SUCCESS.getCode());
apiResult.setMessage(ResponseResultEnum.SUCCESS.getMsg());
apiResult.setData(body);
return apiResult;
}
public static ApiResult successOf(String msg) {
ApiResult apiResult = new ApiResult();
apiResult.setCode(ResponseResultEnum.SUCCESS.getCode());
apiResult.setMessage(msg);
return apiResult;
}
public static ApiResult failOf(String msg) {
ApiResult apiResult = new ApiResult();
apiResult.setCode(ResponseResultEnum.UNKNOW_ERROR.getCode());
apiResult.setMessage(msg);
return apiResult;
}
public static ApiResult failOf(Object data, String msg) {
ApiResult apiResult = new ApiResult();
apiResult.setData(data);
apiResult.setCode(ResponseResultEnum.UNKNOW_ERROR.getCode());
apiResult.setMessage(msg);
return apiResult;
}
public static ApiResult failOf(ResponseResultEnum e, String msg) {
ApiResult apiResult = new ApiResult();
apiResult.setCode(e.getCode());
apiResult.setMessage(msg);
return apiResult;
}
public static <T> ApiResult errorOf(ResponseResultEnum e, T msg) {
ApiResult<T> apiResult = new ApiResult<>();
apiResult.setCode(e.getCode());
apiResult.setMessage(msg.toString());
return apiResult;
}
public static <T> ApiResult status(StatusEnum status, T data) {
ApiResult<T> apiResult = new ApiResult<>();
apiResult.setCode(status.getCode());
apiResult.setMessage(status.getEnName());
apiResult.setData(data);
return apiResult;
}
}
统一异常处理
代码:
依赖少了的,漏了的自己引。
import com.mysql.jdbc.MysqlDataTruncation;
import com.thyc.fabric.common.constant.ApiResult;
import com.thyc.fabric.common.enumeration.ResponseResultEnum;
import com.thyc.fabric.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.util.NestedServletException;
/**
* 全局异常处理
*
* @author Administrator
* @date 2019:08:23 15:01
*/
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.OK)
public ApiResult handleException(Exception e) {
// 缺少访问参数异常
if (e instanceof MissingServletRequestParameterException) {
String msg = e.getMessage().split(" ")[3].replace("'", "");
return ApiResult.errorOf(ResponseResultEnum.PARAMS_ERROR, "缺少访问参数[" + msg + "]");
} else if (e instanceof NestedServletException) {
// 断言处理
String msg = e.getMessage().substring(e.getMessage().lastIndexOf(":") + 1);
msg = msg.replace(" ", "");
return ApiResult.failOf(msg);
} else if (e instanceof MysqlDataTruncation) {
log.error("sql异常:" + e.getMessage(), e);
return ApiResult.failOf("sql异常:" + e.getMessage());
} else if (e instanceof TooManyResultsException) {
log.error("得到多个结果:{}", e.getMessage());
return ApiResult.failOf(e.getMessage());
}
if (e.getMessage() == null) {
return ApiResult.failOf(e + "");
}
return ApiResult.failOf(e.getMessage() + "");
}
/**
* 400错误
*/
@ExceptionHandler({HttpMessageNotReadableException.class, TypeMismatchException.class, MissingServletRequestParameterException.class, MethodArgumentTypeMismatchException.class})
@ResponseStatus(HttpStatus.OK)
public ApiResult requestNotReadable(HttpMessageNotReadableException e) {
log.error("参数异常:" + e.getMessage());
return ApiResult.failOf(ResponseResultEnum.PARAMS_ERROR, e.getMessage());
}
/**
* Throwable拦截器
*/
@ExceptionHandler(Throwable.class)
public ApiResult exceptionHandle(Throwable e) {
String msg = e.getMessage().substring(e.getMessage().lastIndexOf(":") + 1);
msg = msg.replace(" ", "");
return ApiResult.failOf(ResponseResultEnum.SERVER_ERROR, msg);
}
@ExceptionHandler(value = BusinessException.class)
@ResponseStatus(HttpStatus.OK)
public ApiResult businessException(BusinessException e) {
return ApiResult.failOf(e.getMessage());
}
@ExceptionHandler(value = RuntimeException.class)
@ResponseStatus(HttpStatus.OK)
public ApiResult runtimeException(Exception e) {
return ApiResult.failOf(e.toString());
}
/**
* 统一处理请求参数校验(实体对象传参)
*/
@ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.OK)
public ApiResult validExceptionHandler(Exception e) {
BindingResult bindResult = null;
if (e instanceof BindException) {
bindResult = ((BindException) e).getBindingResult();
} else if (e instanceof MethodArgumentNotValidException) {
bindResult = ((MethodArgumentNotValidException) e).getBindingResult();
}
String msg;
if (bindResult != null && bindResult.hasErrors()) {
msg = bindResult.getAllErrors().get(0).getDefaultMessage();
if (msg.contains("NumberFormatException")) {
msg = "参数类型错误";
}
} else {
msg = "系统繁忙,请稍后重试...";
}
return ApiResult.errorOf(ResponseResultEnum.PARAMS_ERROR, msg);
}
@ExceptionHandler(value = UnauthorizedException.class)
@ResponseStatus(HttpStatus.OK)
public ApiResult handleUnauthorizedException(Exception e) {
log.error("权限不足,{}", e.getMessage());
return ApiResult.failOf(ResponseResultEnum.AUTH_ERROR, "权限不足:" + e.getMessage());
}
@ExceptionHandler(value = {AuthenticationException.class, UnauthenticatedException.class})
@ResponseStatus(HttpStatus.OK)
public ApiResult handleAuthorizationException(Exception e) {
log.error("shiro认证失败: {}", e.getMessage());
return ApiResult.failOf(ResponseResultEnum.USER_TOKEN_INVALID, ResponseResultEnum.USER_TOKEN_INVALID.getMsg());
}
}