错误处理

Power Fx 包含一个预览功能,可实现公式级别的错误处理。 默认情况下,此功能在设置中处于启用状态。

“设置”中即将推出的功能的屏幕截图,其中显示“公式级错误管理”设置为“开”。

此设置可访问类似 IfErrorIsErrorErrorIsBlankorError 的公式。 这些函数可用于检测错误、提供替代值或根据错误采取特定操作。

验证错误处理

这些函数有助于验证输入,例如不正确的格式或必填字段。 使用 If 语句或 IsBlankIsError 等函数来验证用户输入。 提供明确的错误信息,并阻止后续处理,直到输入得以纠正。

If( IsBlank(TextInput.Text),
    Notify("Field cannot be blank", 
    NotificationType.Error),
    // Continue with processing
)

Patch 函数错误处理

与上述示例类似,Error 函数在将数据修补到数据源时可帮助捕获错误。 Patch 函数通过两种方式报告错误。

它可以作为操作的结果返回错误值。

UpdateContext(
    {   
    result : Patch(
             Feeds,
             Defaults(Feeds),
             {
                 createdon: Now(),
                 crde8_content: TextInput1_1.Text
                 cr9ce_imageurl: filename
             }
        )
    }
)

您可以使用 IsError 检测错误,并使用 IfError 替换或隐藏它们。

IfError(result, Notify("There was an issue saving data" , NotificationType.Error));
IfError(result, Notify("There was an issue saving data" , & FirstError.Message, NotificationType.Error))

If(
    IsError(
        Patch(
            Feeds,
            Defaults(Feeds),
            {
                createdon: Now(),
                crde8_content: TextInput1_1.Txt,
                cr9ce_imageurl: filename        
            }
        )
    ),
    Notify("Error: There was an issue saving data", NotificationType.Error)
)

表单错误处理

当您使用表单提交数据时,使用 SubmitForm 函数,请使用表单控件属性 OnFailure 通知用户错误消息。

// OnSelect property of the form's submit button
SubmitForm(frm_SubmitData);

// OnSuccess property of the form
Navigate('Success Screen');

// OnFailure property of the form
Notify("Error: the invoice could not be created", NotificationType.Error);

自定义错误消息与 OnError 属性

Power Apps OnError 属性可让您捕获应用程序中所有未处理的错误。 通过 OnError 属性,您可执行一个每当应用程序未处理错误时运行的表达式(例如将错误存储在变量中或使用 IfError 等函数将其替换为其他值)。 若要使用OnError 该属性,需要将其添加到要应用它的应用程序中。 然后,您可以在 OnError 属性框中编写公式来指定要显示的错误信息。

需要注意的是 App.OnError 不能像 IfError 那样替换错误。 在执行 App.OnError 时,错误已经发生,并且结果已经通过其他公式传播。  App.OnError 仅可控制如何将错误报告给最终用户,并在需要时为制作者提供记录错误的挂钩。

此代码在 App.OnError 上可帮助定位错误的来源:

Notify(
    Concatenate(
        FirstError.Message,
        ", Observed: ",
        FirstError.Observed,
        ", Source: ",
        FirstError.Source
    ),
    NotificationType.Error
)

Power Fx 错误处理

下一步