前后端分离开发之后端华丽控制面板显示请求响应以及异常信息

闲的蛋疼的日子总想搞点那么点事情,这就搞了一个比较鸡肋的控制面板请求日志功能,话不多说直接开整。
运行样式:
在这里插入图片描述
在这里插入图片描述
看到这里如果感兴趣的老铁可以继续往下看

首先基于环境:SpringBoot,Maven

  • 1.加入相关依赖
<!-- SpringBoot -->
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
 </parent>
<!-- json处理-->
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
</dependency>
<!-- web -->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
</dependency>
        <!-- 代码简化 -->
<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
</dependency>
  • 2.创建一个Aop处理类
@Aspect
@Slf4j
@Component
public class WebLogImpl {


    private static JSONObject jsonObject;

    //切入点 Controller所有的方法
    @Pointcut("execution(* yq.market.core.controller..*.*(..))")
    private void webControllerPointcut() {
    }

    @Around(value = "webControllerPointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        //这三步就是获取HttpServletRequest对象是使用的
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        if(jsonObject == null){
            jsonObject = new JSONObject();
        }
        //字符串拼接
        StringBuffer requestURL = request.getRequestURL();
        //请求类型
        String method = request.getMethod();
        //content-type类型
        String header = request.getHeader("content-type");
        //所有参数值
        Object[] args = proceedingJoinPoint.getArgs();
        //得到对象
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取所有参数名称
        String[] parameterNames = methodSignature.getParameterNames();
        //循环拼接参数字符串
        for(int i = 0 ; i < parameterNames.length ; i++){
            jsonObject.put(parameterNames[i],args[i].toString());
        }
        String paramJson = jsonObject.toJSONString();
        //保存运行结果对象
        Object proceed = null;
        try{
            //记录日志
            System.out.println("\n");
            log.info("发起请求----> url:{} <--> content-type: {} <--> method:{} <--> params:{}",requestURL.toString(),header,method,paramJson);
            //调用方法获得执行结果
            proceed = proceedingJoinPoint.proceed();
            log.info("响应请求----> url:{} <--> data:{}",requestURL.toString(),proceed);
            return proceed;
        }catch (Throwable th){
            //获取异常信息
            String message = th.getMessage();
            //得到异常全类名
            String name = th.getClass().getName();
            log.info("发生异常----> url:{} <--> errorType:{} <--> errorMessage:{}",requestURL.toString(),name,message);
            //抛出异常给全局异常处理
            throw th;
        }
    }

}
  • 3.创建一个获取异常信息的处理类
@Slf4j
@ResponseBody
public class DIYExceptionHandler extends BaseApiService {

    //截取异常关键信息
    protected String errorDescribe(Throwable throwable){
        String name = throwable.getClass().getName();
        String message = throwable.getMessage();
        StackTraceElement stackTraceElement = throwable.getStackTrace()[0];
        String methodName = stackTraceElement.getMethodName();
        String className = stackTraceElement.getClassName();
        int lineNumber = stackTraceElement.getLineNumber();
        String format = String.format("异常描述----> 程序在执行到 %s 中的 %s 方法第 %s 行的时候报错:%s", className, methodName, lineNumber, message);
        return format;
    }

    //统一返回
    protected ResponseBase unifiedReturn(Throwable throwable, String message){
        log.error(errorDescribe(throwable));
        ResponseBase responseBase = setResultError(message);
        log.info("异常响应----> {}",responseBase);
        return responseBase;
    }

}
  • 4.创建一个全局异常处理类
@ControllerAdvice
public class ExceptionHandler extends DIYExceptionHandler {

    @Override
    protected String errorDescribe(Throwable throwable) {
        return super.errorDescribe(throwable);
    }

    @Override
    protected ResponseBase unifiedReturn(Throwable throwable, String message) {
        return super.unifiedReturn(throwable, message);
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    ResponseBase handleException(Exception e) {
        return unifiedReturn(e,"内部发生致命错误-->"+e.getMessage());
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(IllegalArgumentException.class)
    ResponseBase IllegalArgumentException(IllegalArgumentException e) {
        return unifiedReturn(e,"参数错误");
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(AccessDeniedException.class)
    ResponseBase AccessDeniedException(AccessDeniedException e) {
        return unifiedReturn(e,"没有授权的访问");
    }
//可以在这里添加需要处理的类型
}

到了这里我么基本上大致的内容就完成了
另外这里使用的统一返回格式ResponseBase(BaseApiService):请点击我
注解解释:
@Aspect:开启SpringAOP
@Slf4j:lombok中的注解,就是log4j日子的简化注解版
@Component:注入到Spring容器中
@Pointcut:切面
@Around:环绕增强
@ResponseBody:返回为String类型
@ControllerAdvice:全局异常处理,经常搭配@ExceptionHandler达到全局异常处理
@ExceptionHandler:同上

~到了这里就要说再见了,谢谢大家的观看,有不足的地方请指出,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值