我想列印正確的檔案路徑,即使該函式是在其他模塊中匯入的,以便正確處理錯誤。我怎樣才能做到這一點?我正在使用無服務器堆疊。
請參考以下代碼,
class Logger {
filePath: string;
constructor(fp: string) {
filePath = fp;
}
printLog(info) {
const { timestamp, message } = info;
return `${timestamp} ${filePath}: ${message}`;
}
}
這用于dbConnection.ts,
const logger = new Logger(__filename);
export const connectToDB = () => {
try {
//DB connection code.
} catch(error) {
logger.print({ timestamp: new Date().toISOString(), message: error.message });
}
};
現在,我想從其他模塊連接到 db,可以說,test.ts然后我將按如下方式使用它,
export const test = () => {
//some code here...
connectToDB();
}
當連接到資料庫時發生錯誤時,它會列印出類似這樣的內容,
2022-05-27T05:24:47.548Z src/test.ts: Error in connecting DB url is unreachable please check your internet connection.
為了具有適當的可除錯性,我想列印實際拋出例外的檔案名。那是src/dbConnection.ts和不是src/test.ts。
uj5u.com熱心網友回復:
嘗試使用this@zyp 建議的方式更改記錄器類。
class Logger {
constructor(fp: string) {
this.filePath = fp;
}
printLog(info) {
const { timestamp, message } = info;
return `${timestamp} ${this.filePath}: ${message}`;
}
}
uj5u.com熱心網友回復:
嘗試使用
__filename
__filename:這將回傳執行檔案的路徑
__dirname:這將回傳執行檔案所在目錄的路徑。
檢查它是否符合您的需要
console.log(__filename);
uj5u.com熱心網友回復:
嘗試在您的 Logger 類中更改filePath為this.filePath
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481457.html
標籤:javascript 节点.js 打字稿 网页包 ecmascript-6
上一篇:打字稿中的條件重疊
