我正在嘗試構建可變數量的引數例程,以獲得更好的背景關系錯誤訊息。
我正在尋找可以在 NodeJS 中運行的 JavaScript 解決方案。
讓我先用代碼解釋一下我的要求:
在檔案 licenseNotificationMessages.js 中
const licenseNotificationMessages = {
CapacityAlmostExpired:{
description: ?'my description contains $1 followed by $2 followed by $3 in this case.,
},
CapacityExpired:{
description: ?'my description contains $1 followed by $2 in this case.,
},
}
const constructMessage = (message, ...var_args_array) => {
// TODO. Replace the message's occurrences of $1, $2, $3 ... $N by var_args_array[0],
// var_args_array[1], .... var_args_array[N].
}
module.exports = {
licenseNotificationMessages,
constructMessage,
}
我想使用它,例如:
在另一個檔案中匯出 licenseNotificationMessages
const { licenseNotificationMessages, constructMessage } = require('./licenseNotificationMessages');
description = licenseNotificationMessages.constructMessage(licenseNotificationMessages.CapacityAlmostExpired.description, ['val_for_$1', 'val_for_$2', 'val_for_$3']);
......
description = licenseNotificationMessages.constructMessage(licenseNotificationMessages.CapacityExpired.description, ['val_for_$1', 'val_for_$2']);
不知道如何在 Node JS 環境中用 JavaScript 實作它。(我在節點 16 )。
任何指標在這里都會有所幫助。
uj5u.com熱心網友回復:
錯誤類別
在我看來,當有不同的錯誤和不同的訊息時,定義一些錯誤類通常是最好的解決方案:
export class CustomError extends Error {
constructor(...args) {
super(`Some message with ${args[0]} and ${args[1]} mentioned in it`);
};
}
export class CapacityAlmostExpiredError extends Error {
constructor(capacityUsed, capacityLimit) {
super(`Used capacity (${capacityUsed} MB) almost exceeds the limit of ${capacityLimit} MB`);
};
}
console.log 帶占位符
console.log 在這種情況下有一個非常優雅的 API,但它也有很大的缺點(稍后會詳細介紹):
console.log(messageWithPlaceholders, ...args);

在您的情況下,它將是:
const message = "my description contains %s followed by %s followed by %s in this case."; // notice lack of numbers
console.log(message, 'val_for_the_first_%s', 'val_for_the_second_%s', 'val_for_the_third_%s');
缺點:
- 這是日志記錄,而不是字串創建, - 在記錄之前您無權訪問該字串;
console.log在生產代碼中經常被禁止;- 您必須將占位符模式更改為 %,而不是 $;
迭代引數
綜上所述,如果constructMessage無論出于何種原因,該方法是絕對必要的,則必須迭代引數串列,獲取每個引數的索引,將索引轉換為占位符,在字串中找到該占位符,然后將其替換為引數值:
function constructMessage(string, args) {
let message = string;
for (const [ index, arg ] of args.entries()) {
const placeholder = "$" (index 1); // 0 becomes '$1'
message = message.replace(placeholder, arg);
}
return message;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350389.html
標籤:javascript 节点.js
