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;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM