接口拦截 日志打印 自定义异常输出
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
package cn.ysk.cashier.config;
|
||||
|
||||
import cn.ysk.cashier.utils.FastJsonUtils;
|
||||
import cn.ysk.cashier.utils.SpringContextHolder;
|
||||
import cn.ysk.cashier.utils.StringUtils;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.Signature;
|
||||
@@ -16,8 +15,8 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 方法调用统一切面处理
|
||||
@@ -40,93 +39,35 @@ public class AppApiMethodAspect {
|
||||
|
||||
@Around("pkg()")
|
||||
// @SuppressWarnings("unchecked")
|
||||
public Object around(ProceedingJoinPoint pjp) throws Throwable {
|
||||
Object[] args = pjp.getArgs();
|
||||
public Object around(ProceedingJoinPoint pjp) throws JsonProcessingException {
|
||||
HttpServletRequest req = SpringContextHolder.getRequest();
|
||||
Signature sign = pjp.getSignature();
|
||||
MethodSignature ms = (MethodSignature) sign;
|
||||
Object result;
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 设置忽略空值
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
Object result = null;
|
||||
try {
|
||||
// 获取方法参数
|
||||
Object[] args = pjp.getArgs();
|
||||
String[] paramNames = ms.getParameterNames();
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
params.put(paramNames[i], FastJsonUtils.toJSONString(args[i]));
|
||||
}
|
||||
// 执行被拦截的方法
|
||||
result = pjp.proceed();
|
||||
ResponseEntity<?> responseEntity = (ResponseEntity<?>) result;
|
||||
Object responseBody = responseEntity.getBody();
|
||||
log.info("\n>>>>>>{} {}\n>>>>>>{}\n>>>>>>Request: {}\n>>>>>>Response: {}"
|
||||
, req.getMethod(), req.getRequestURL(), req.getRemoteAddr(),
|
||||
mapper.writeValueAsString(args),
|
||||
mapper.writeValueAsString(responseBody)
|
||||
FastJsonUtils.toJSONString(params),
|
||||
FastJsonUtils.toJSONString(result)
|
||||
);
|
||||
} catch (Throwable e) {
|
||||
result = getReturnObject(ms.getReturnType(), HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
log.warn("{}", e);
|
||||
log.error("\n>>>>>>{} {}\n>>>>>> {}\n>>>>>>Request: {}\n>>>>>>Exception: {}"
|
||||
, req.getMethod(),
|
||||
req.getRequestURL(),
|
||||
req.getRemoteAddr(),
|
||||
mapper.writeValueAsString(args),
|
||||
e);
|
||||
log.error("\n>>>>>>{} {}\n>>>>>>{}\n>>>>>>Request: {}\n>>>>>>Exception: {}"
|
||||
, req.getMethod(), req.getRequestURL(), req.getRemoteAddr(),
|
||||
FastJsonUtils.toJSONString(params),
|
||||
e.getMessage());
|
||||
ResponseEntity<String> body = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
|
||||
return body;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反射封装方法的返回值
|
||||
*
|
||||
* @param clz 方法返回值的字节码对象
|
||||
* @param _enum 错误信息
|
||||
* @param <T> 返回值类型
|
||||
* @return 返回原方法的返回对象
|
||||
*/
|
||||
@SuppressWarnings("SameParameterValue") // 忽略枚举只传入了一个值的异常
|
||||
private <T> T getReturnObject(Class<T> clz, HttpStatus _enum) {
|
||||
if (clz.getName().equals("void")) { //没有返回值时
|
||||
return null;
|
||||
}
|
||||
T t = null;
|
||||
try {
|
||||
t = clz.newInstance();
|
||||
} catch (InstantiationException | IllegalAccessException e) {
|
||||
log.warn("{}", e);
|
||||
}
|
||||
//设置错误码
|
||||
setFiledValue("code", _enum.value(), t);
|
||||
//设置错误信息
|
||||
setFiledValue("message", _enum.getReasonPhrase(), t);
|
||||
return t;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用setXX方法设置属性
|
||||
*
|
||||
* @param fileName 方法名
|
||||
* @param value 方法值
|
||||
* @param obj 返回对象
|
||||
*/
|
||||
private void setFiledValue(String fileName, Object value, Object obj) {
|
||||
//该方式找不到对应字段不会报错
|
||||
if (StringUtils.isBlank(fileName)) {
|
||||
return;
|
||||
}
|
||||
//转成SetXXX方法名
|
||||
char[] chars = fileName.toCharArray();
|
||||
chars[0] = (char) (chars[0] - 32); //首字母转大写
|
||||
//拼接成方法名
|
||||
String methodName = "set" + String.copyValueOf(chars);
|
||||
Class<?> clz = obj.getClass();
|
||||
Method[] declaredMethods = clz.getMethods();
|
||||
for (Method method : declaredMethods) {
|
||||
boolean equals = method.getName().equals(methodName);
|
||||
if (equals) {
|
||||
try {
|
||||
method.invoke(obj, value);
|
||||
} catch (IllegalAccessException | InvocationTargetException e) {
|
||||
log.warn("{}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class DictController {
|
||||
@Log("新增字典")
|
||||
@ApiOperation("新增字典")
|
||||
@PostMapping
|
||||
@PreAuthorize("@el.check('dict:add')")
|
||||
// @PreAuthorize("@el.check('dict:add')")
|
||||
public ResponseEntity<Object> createDict(@Validated @RequestBody Dict resources){
|
||||
if (resources.getId() != null) {
|
||||
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
|
||||
|
||||
Reference in New Issue
Block a user