【问题标题】:Inspect template strings before concatenation在连接之前检查模板字符串
【发布时间】:2019-10-08 10:00:30
【问题描述】:

我正在生成如下错误消息:

throw `Do not recognize eventType '${eventType}', recognized events are ${recognizedEvents}.`;

问题是承认Events是一个对象,但它只是toString'ed...无论如何,所以我可以这样做:

throw `Do not recognize eventType '${eventType}', recognized events are ${util.inspect(recognizedEvents)}.`;

问题不仅在于它更冗长 - 有时我只是忘记调用 util.inspect()。如果直接传递对象,即使 TypeScript 也让我编译模板文字。这里有什么好的技术可以确保对象在日志中的合理深度得到检查?

【问题讨论】:

    标签: node.js template-literals


    【解决方案1】:

    您是否更有可能记住在每个模板字符串中使用tagged template 而不是util.inspect

    function err(strings, eventType, recognizedEvents) {
    
      return `${strings[0]}${eventType}${strings[1]}${util.inspect(recognizedEvents)}`;
    }
    
    throw err`Do not recognize eventType '${eventType}', recognized events are ${recognizedEvents}.`;
    

    结合@JackBashford 建议使用JSON.stringify 而不是util.inspect,您可以将对象字符串化得尽可能深。

    【讨论】:

    • @OlegzandrDenman 文档对它的解释比我以往任何时候都好,但是通过在模板字符串前面加上该函数,所有纯字符串都被推入 strings 数组,并且任何表达式都是附加参数到标签函数。
    猜你喜欢
    • 2011-01-12
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2020-02-17
    • 1970-01-01
    相关资源
    最近更新 更多