zoukankan      html  css  js  c++  java
  • SpringBootWEB项目和非Web项目的全局异常捕获

    一、简介

      SpringBoot的WEB异常捕获,如果是WEB项目的话,可以直接处理Controller中的异常。如果不是WEB项目的话,就需要使用AspectJ来做切面。

    二、WEB项目

    package com.test.handler;
    
    import lombok.extern.log4j.Log4j2;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    
    @ControllerAdvice
    @Log4j2
    public class GlobalExceptionHandler {
        @ExceptionHandler(value = Exception.class)
        public String exception(Exception e, Model model){
            log.error("find exception:e={}",e.getMessage());
            model.addAttribute("mes",e.getMessage());
            return "pages/500";
        }
    }

    三、非WEB项目

    package com.test.syncbackend.handler;
    
    import lombok.extern.log4j.Log4j2;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    @Component
    @Aspect
    @Log4j2
    public class GlobalExceptionHandler {
    
        @Pointcut("execution(* com.test.syncbackend.scheduleds.*.*(..))")
        public void pointCut() {
        }
    
        @Around("pointCut()")
        public Object handlerException(ProceedingJoinPoint proceedingJoinPoint) {
            try {
                return proceedingJoinPoint.proceed();
            } catch (Throwable ex) {
                log.error("execute scheduled occur exception.", ex);
            }
            return null;
        }
    }
  • 相关阅读:
    C语言的AES加密
    curl指定域名的IP
    gdb调试知识
    C++获取寄存器eip的值
    C++嵌入lua
    [置顶] python字典和nametuple互相转换例子
    【python】redis基本命令和基本用法详解
    xshell登录到CentOS7上时出现“The remote SSH server rejected X11 forwarding request.
    selinue引起的ssh连接错误
    SCP和SFTP相同点和区别
  • 原文地址:https://www.cnblogs.com/songxingzhu/p/9718670.html
Copyright © 2011-2022 走看看