统一异常处理和信息返回
如下是我在项目中使用的统一处理和信息返回模板
https://gitee.com/Grantr/unified-handing.git
Constans
Constans
package com.shenhua.Constants;
/**
* Constant class
*/
public interface Constants {
/**----------------------------------------通用状态码----------------------------------------**/
/**
* 响应成功
*/
String HTTP_SUCCESS = "200";
/**
* 未授权
*/
String HTTP_UNAUTHORIZED = "401";
/**
* 资源未找到
*/
String HTTP_NOT_FOUND = "404";
/**
* 服务器错误
*/
String HTTP_SERVER_ERROR = "500";
/**-----------------------------------------------业务相关异常----------------------------------------------**/
String INVALID_CODE = "10000";
String USERNAME_NOT_EXISTS = "10001";
String USER_CREDIT_NOT_ENOUTH = "10002";
enum ResultCode {
/**
* 统一定义返回返回信息枚举
*/
SUCCESS(Constants.HTTP_SUCCESS, "请求成功"),
UNAUTHORIZED(Constants.HTTP_UNAUTHORIZED, "未授权"),
NOT_FOUND(Constants.HTTP_NOT_FOUND, "资源未找到"),
SERVER_ERROR(Constants.HTTP_SERVER_ERROR, "服务器错误"),
/**
* 业务相关异常
*/
INVALID_CODE(Constants.INVALID_CODE,"验证码无效"),
USERNAME_NOT_EXISTS(Constants.USERNAME_NOT_EXISTS,"用户名不存在"),
USER_CREDIT_NOT_ENOUTH(Constants.USER_CREDIT_NOT_ENOUTH,"用户积分不足");
private String code;
private String message;
ResultCode(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
}
}
exception
AppException
package com.shenhua.exception;
import com.shenhua.Constants.Constants;
/**
* @Author Akio
* @Description
* 来自业务中的异常
* 继承自RuntimeException ,后续对AppException的使用就不需要做异常抛出
* 目前所有的业务异常枚举都定义在Constants
* 就是为了给GlobalExceptionHandler中做是否是业务异常的判定
*/
public class AppException extends RuntimeException{
private String code = "500";
private String message = "服务器异常";
public AppException(Constants.ResultCode appExceptionCodeMsg){
super();
this.code = appExceptionCodeMsg.getCode();
this.message = appExceptionCodeMsg.getMessage();
}
public AppException(String code,String message){
super();
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
GlobalExceptionHandler
package com.shenhua.exception;
import com.shenhua.Constants.Constants;
import com.shenhua.response.JSONData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public <T> JSONData<T> exceptionHandler(Exception e) {
//这里先判断拦截到的Exception是不是我们自定义的异常类型
if (e instanceof AppException) {
AppException appException = (AppException) e;
return JSONData.error(appException.getCode(), appException.getMessage());
}
if (e instanceof RuntimeException) {
return JSONData.error("RuntimeException", e.getMessage());
}
//如果拦截的异常不是我们自定义的异常(例如:数据库主键冲突)
return JSONData.error(Constants.ResultCode.SERVER_ERROR);
}
}
response
JSONData
package com.shenhua.response;
import com.shenhua.Constants.Constants;
import java.util.HashMap;
/**
* 用户数据返回的实体
*/
public class JSONData<T> {
private String code;
private String message;
private T result;
private final Long timestamp;
public JSONData() {
this(Constants.ResultCode.SUCCESS);
}
public JSONData(T result) {
this(Constants.ResultCode.SUCCESS, result);
}
/**
* 使用提供的Constants
* @param resultCode
*/
public JSONData(Constants.ResultCode resultCode) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.result = null;
this.timestamp = System.currentTimeMillis();
}
/**
* 使用提供的Constants,并附result
* @param resultCode
* @param result
*/
public JSONData(Constants.ResultCode resultCode, T result) {
this.code = resultCode.getCode();
this.message = resultCode.getMessage();
this.result = result;
this.timestamp = System.currentTimeMillis();
}
/**
* 自己提供code和message
* @param resultCode
* @param message
*/
public JSONData(String resultCode, String message) {
this.code = resultCode;
this.message = message;
this.result = null;
this.timestamp = System.currentTimeMillis();
}
/**--------------------------直接使用------------------------------*/
public static <T> JSONData<T> success(T result) {
return new JSONData<>(Constants.ResultCode.SUCCESS, result);
}
public static <T> JSONData<T> error(Constants.ResultCode errorCode) {
return new JSONData<>(errorCode);
}
public static <T> JSONData<T> error(String errorCode, String message) {
return new JSONData<>(errorCode, message);
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getTimestamp() {
return timestamp;
}
public JSONData<T> code(Constants.ResultCode errorCode) {
this.code = errorCode.getCode();
this.message = errorCode.getMessage();
return this;
}
public JSONData<T> message(String message) {
this.message = message;
return this;
}
public JSONData<T> result(T result) {
this.result = result;
return this;
}
public HashMap<String, Object> resultGet() {
if (this.result instanceof HashMap) {
return (HashMap<String, Object>) this.result;
}
return new HashMap<>();
}
public boolean hasKeyOfData(String key) {
return this.resultGet().containsKey(key);
}
}
Controller
DemoController
package com.shenhua.controller;
import com.shenhua.Constants.Constants;
import com.shenhua.exception.AppException;
import com.shenhua.response.JSONData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class DemoController {
@GetMapping("demo")
public JSONData<String> demo1(String name) {
if ("ok".equals(name)) {
return JSONData.success("success result");
}
if ("errcode".equals(name)) {
//抛业务相关的异常
throw new AppException(Constants.ResultCode.INVALID_CODE);
}
if ("0".equals(name)) {
int i = 1 / 0;
}
//检查用户积分是否足够,如果不够,就抛出异常
if ("notenough".equals(name)) {
throw new AppException(Constants.ResultCode.USER_CREDIT_NOT_ENOUTH);
}
return JSONData.success("default");
}
@GetMapping("list")
public JSONData<List> list() {
List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
return JSONData.success(list);
}
}