1、自定义异常
/**
* @ClassName MyException
* @Description 自定义异常类
* @Author 洛城天使
* @Date 2021/9/21 16:25
* @Version 1.0
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class MyException extends RuntimeException {
private String code; //异常状态码
private String message; //异常信息
private String method; //发生的方法,位置等
private String description; //描述
public MyException(String code, String message, String method, String description) {
this.code = code;
this.message = message;
this.method = method;
this.description = description;
}
}
2、全局异常处理器
/**
* @ClassName GlobalExceptionHandler
* @Description 全局异常处理器
* @Author 洛城天使
* @Date: 2021/9/21 16:16
* @Version 1.0
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* 捕获并处理自定义异常
*/
@ExceptionHandler(MyException.class)
public String handleMyException(MyException e) {
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("message", e.getMessage());
map.put("method", e.getMethod());
map.put("description", e.getDescription());
logger.error(e.getCode());
logger.error(e.getMessage());
logger.error(e.getMethod());
logger.error(e.getDescription());
return MsgUtil.errorMsg(map);
}
/**
* 处理所有异常
*/
@ExceptionHandler(Exception.class)
public void handleException(Exception e) {
e.printStackTrace();
logger.error(e.toString());
}
}
3、返回值工具类
/**
* @Description 返回Json字符串工具类
* @Author 洛城天使
* @Date 2021/9/21 16:25
* @Version 1.0
**/
public class MsgUtil {
/**
* 传入String可变参数的返回值
*/
public static String successMsg(String... str) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "ok");
if (str.length == 0) {
return jsonObject.toJSONString();
} else if (str.length == 1) {
jsonObject.put("data", str[0]);
return jsonObject.toJSONString();
} else if (str.length % 2 != 0) {
return "请输入大于1的偶数个参数";
} else {
for (int i = 0; i < str.length; i++) {
jsonObject.put(str[i], str[i++]);
}
}
return jsonObject.toJSONString();
}
/**
* 传入Map参数的返回值
*/
public static String successMsg(Map map) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "ok");
jsonObject.put("data", JSONObject.parseObject(JSON.toJSON(map).toString()));
return jsonObject.toJSONString();
}
/**
* 传入List参数的返回值
*/
public static String successMsg(List list) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "ok");
jsonObject.put("data", new JSONArray().addAll(list));
return jsonObject.toJSONString();
}
public static String errorMsg() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "error");
return jsonObject.toJSONString();
}
public static String errorMsg(String failInfo) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "error");
jsonObject.put("info", failInfo);
return jsonObject.toJSONString();
}
public static String errorMsg(Map map) {
return JSONObject.parseObject(JSON.toJSON(map).toString()).toJSONString();
}
}