1、全局切面打印接口耗时
@Component
@Aspect
@Slf4j
public class ServiceAspectHandler {
@Pointcut("execution(public * com.winning.mns.controller..*.*(..))")
public void managerLogAop() {
}
@Around("managerLogAop()")
public Object timing(ProceedingJoinPoint joinPoint) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
String clientIp = ServletUtil.getClientIP(request);
Object object;
StopWatch stopWatch = new StopWatch();
stopWatch.start();
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
object = joinPoint.proceed();
stopWatch.stop();
log.info("API:{}.{} execute time:{}ms,IP:{}", className, methodName, stopWatch.getTotalTimeMillis(), clientIp);
return object;
}
}
2、全局异常捕获
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice("com.winning.mns")
public class MyExceptionHandler {
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler({MethodArgumentNotValidException.class})
public WphResponseMessage bindException(MethodArgumentNotValidException e) {
StackTraceElement stackTraceElement = e.getStackTrace()[0];
String className = stackTraceElement.getClassName();
String methodName = stackTraceElement.getMethodName();
BindingResult bindingResult = e.getBindingResult();
log.error("参数异常信息:{}", e.getMessage());
return BusinessUtils.getFailResult(bindingResult.getFieldError().getDefaultMessage(), className + "." + methodName, 3);
}
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.OK)
public WphResponseMessage exceptionHandler(Exception e) {
StackTraceElement stackTraceElement = e.getStackTrace()[0];
String className = stackTraceElement.getClassName();
String methodName = stackTraceElement.getMethodName();
log.error("业务异常信息:{}", e.getMessage(), e);
return BusinessUtils.getFailResult("系統发生异常:" + e.getMessage(), className + "." + methodName, 3);
}