Errors

Power Query M 公式语言中的 错误 表明计算表达式的过程无法生成值。 错误由遇到 错误 条件的运算符和函数或使用 错误 表达式引发。 使用 try 表达式处理错误。 引发错误时,指定了一个值,该值可用于指示错误发生的原因。

试用表达式

try 表达式将值和错误转换为记录值,该值指示 try 表达式是否处理错误,以及处理错误时提取的正确值或错误记录。 例如,请考虑引发错误的以下表达式,然后立即处理它:

try error "negative unit count"

此表达式的计算结果为以下嵌套记录值,解释 [HasError], [Error]之前单价示例中的和 [Message] 字段查找。

错误记录

[
    HasError = true,
    Error =
        [  
            Reason = "Expression.Error",
            Message = "negative unit count",
            Detail = null
        ]
]

常见情况是将错误替换为默认值。 try 表达式可以与可选的其他子句一起使用,以精简形式实现该表达式:

try error "negative unit count" otherwise 42
// equals 42

错误示例

let Sales =
        [
        ProductName = "Fishing rod",
            Revenue = 2000,
            Units = 1000,
            UnitPrice = if Units = 0 then error "No Units"
                    else Revenue / Units
        ],

    //Get UnitPrice from Sales record
        textUnitPrice = try Number.ToText(Sales[UnitPrice]),
    Label = "Unit Price: " &
        (if textUnitPrice[HasError] then textUnitPrice[Error][Message]
        //Continue expression flow
            else textUnitPrice[Value])
in
    Label

前面的示例访问 Sales[UnitPrice] 字段并设置生成结果的值的格式:

"Unit Price: 2"

如果“单位”字段为零,则该 UnitPrice 字段将引发一个错误,该错误将由尝试处理。 然后,生成的值为:

"No Units"