獲取異常發生所在的類名、方法名、行數

package com.dtream.easycodetest.global;

import com.dtream.easycodetest.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalException {
    @ExceptionHandler(ServiceException.class)
    public String serviceExceptionHandler(ServiceException e) {
        StackTraceElement stackTraceElement = e.getStackTrace()[0];
        // 獲取類名
        String className = stackTraceElement.getClassName();
        String filePath = stackTraceElement.getFileName();
        int lineNumber = stackTraceElement.getLineNumber();
        String methodName = stackTraceElement.getMethodName();
        log.info("類名:{},文件路徑:{},行數:{},方法名:{}", className, filePath , lineNumber, methodName);
        return "類名:" + className + ",文件路徑:" + filePath + ",行數:" + lineNumber + "方法名:" + methodName;
    }
}
相關文章
相關標籤/搜索