错误处理

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
)

下一步