乐趣区

关于异常处理:获取异常发生所在的类名方法名行数

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 fileName = stackTraceElement.getFileName();
        int lineNumber = stackTraceElement.getLineNumber();
        String methodName = stackTraceElement.getMethodName();
        log.info("类名:{}, 文件名:{}, 行数:{}, 办法名:{}", className, fileName, lineNumber, methodName);
        return "类名:" + className + ",文件名:" + fileName + ", 行数:" + lineNumber + "办法名:" + methodName;
    }
}
退出移动版