KEMBAR78
Error Handling | PDF | Computing | Computer Programming
0% found this document useful (0 votes)
25 views14 pages

Error Handling

This article discusses error handling in Power Apps, emphasizing the importance of managing errors to ensure app functionality despite unexpected issues. It explains how to detect, report, and handle errors using various functions like IfError and App.OnError, providing examples of how to implement these strategies in a Canvas app. Additionally, it covers error propagation, observation, and reporting, highlighting the differences between handling errors in Power Apps compared to Excel.

Uploaded by

Desert Wolf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views14 pages

Error Handling

This article discusses error handling in Power Apps, emphasizing the importance of managing errors to ensure app functionality despite unexpected issues. It explains how to detect, report, and handle errors using various functions like IfError and App.OnError, providing examples of how to implement these strategies in a Canvas app. Additionally, it covers error propagation, observation, and reporting, highlighting the differences between handling errors in Power Apps compared to Excel.

Uploaded by

Desert Wolf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Error handling

Article • 03/22/2024

0 Note
The behavior that this article describes is available only when the Formula-level error
management preview feature through Settings > Upcoming features > Preview is turned
on. More information: Controlling which features are enabled

Errors happen. Networks go down, storage fills up, unexpected values flow in. lt's important
that your logic continues to work properly in the face of potential issues.

By default, errors flow through the formulas of an app and are reported to the end user of the
app. In this way, the end user knows something unexpected happened, they can potentially fix
the problem themselves with a different input, or they can report the problem to the owner of
the app.

As an app maker, you can take control of errors in your app:

• Detecting and handling an error. lf there's a chance an error may occur, the app's
formulas can be written to detect the error condition and retry the operation. The end
user doesn't need to be concerned that an error occurred because the maker took the
possibility into account. This is done with the lfError, lsError, and lsErrorOrBlank
functions within a formula.
• Reporting an error. lf an error isn't handled in the formula where it was encountered, the
error is then bubbled up to the App.OnError handler. Here, the error can no langer be
replaced as it has already occurred and is a part of formula calculations. But you can use
App.OnError to control how the error is reported to the end user, including suppressing
the error reporting all together. App.OnError also provides a common choke point for
error reporting across the entire app.
• Creating and rethrowing an error. Finally, you may detect an error condition with your
own logic, a condition that is specific to your app. Use the Error function to create
custom errors. The Error function is also used to rethrow an error after being interrogated
in lfError or App.OnError.

Getting started
Let's start with a simple example.

1. Create a new screen in a Power Apps Canvas app.


2. Insert a Textinput control. lt will default to the name Textlnput1.
3. Insert a Label control.
4. Set the Text property of the Label control to the formula

Power Fx

1/Value( Textinputl.Text)

Text v = jxv 1/Value( Textinput1.Text )

Tree view X @ The value 'Textinput' cannot be converted to a number. X

Screens Components
1 Textinput
1 P Search

+
Ef' App

fJ v O Screen1

0 Label3

==JJ Textlnput1

We have an error because the default text of a Textinput control is "Text input", which can't
be converted to a number. By default this is a good thing: the end user will get a notification
that something isn't working as expected in the app.

Obviously, we don't want an error to greet the user each time they start this app. Likely "Text

input" isn't the right default for the text input box anyway. To remedy this, let's change the
Default property of the Textinput control to:

Power Fx

Blank()

Default v = jxv Blank()

Tree view X @ Invalid operation: division by zero. X

Screens Components

1 P Search

+
Ef' App

tJ v O Screen1

0 Label3

==JJ Textlnput1

Hmm, now we have a different error. Mathematical operations with blank, such as division, will
coerce the blank value to a zero. And that is now causing a division by zero error. To remedy
this, we need to decide what the appropriate behavior is for this situation in this app. The
answer may be to show blank when the text input is blank. We can accomplish this by
wrapping our formula with the lfError function:

Power Fx
IfError( 1/Value( Textinputl.Text), Blank())

Text v - jxv IfError( 1/Value( Textlnput1.Text ), Blank() )

Tree view X

Screens Components

1 P Search

+ [fl App

E) v O Screen1

(2j Label3

==JJ Textlnput1

Now the error is replaced with a valid value and the error banner has gone away. But, we may
have overshot, the lfError we used covers all errors, including typing in a bad value such as
"hello". We can address this by tuning our lfError to handle the division by zero case only
with and rethrowing all other errors:

Power Fx

IfError( 1/Value( Textinputl.Text),


If( FirstError.Kind = ErrorKind.Div0, Blank(), Error( FirstError)))

Text Jxv IfError( 1/Value( Textlnput1.Text ), If( FirstError.Kind = Div0, Blank(), Error( FirstError ) ) )

Tree view X

Screens Components

1 P Search

+
[fl App

v D Screen 1
fJ

{2j Labell

�JJ Textlnput1

So, let's run our app and try some different values.

Without any value, as when the app starts, there's no answer displayed as the default value is
blank, but there also no error shown as the lfError replaces the division by zero error.
::: Power Apps I Canvas

1 1

lf we type in a 4, we get the expected result of 0.25:

::: Power Apps I Canvas

1
0 .. 25

And if we type in something illegal, like hello, then we'II receive an error banner:

::: Power Apps I Canvas

@ The value 'hello' cannot be converied to a number.

hello
This is a simple introductory example. Error handling can be done many different ways,
depending on the needs of the app:

1. lnstead of an error banner, we could have shown "#Error" in the label control with the
formula. To keep the types of the replacements compatible with the first argument to
lfError we need to explicitly convert the numerical result to a text string with the Text
function.

Power Fx

IfError( Text( 1/Value( Textinputl.Text)),


If( FirstError.Kind = ErrorKind.Div0, Blank(), "#Error" )

Text v = Jxv IfError( Text( 1/Value( Textinputl.Text ) ), If( FirstError.Kind = Div0, Blank(), "#Error" ) )

- Treeview X
Screens Components
1 helle
Search
1 P
+ EP App

lJ v O Screen1

[2i Label3

ajJ Textlnput1

2. lnstead of wrapping this specific instance with lfError we could have written a centralized
App.OnError handler. We can't replace the string shown with "#Error" as the error has
already happened and App.OnError is only provided to control reporting.

Power Fx

If( FirstError.Kind <> ErrorKind.Div0, Error( FirstError))

Error propagation
Errors flow through formulas much as they do in Excel. For example in Excel, if cell Al has the
formula =1/0, then A 1 will display the error value #DIV0! :

1 Al v 1 1
= .._... fx i 1 =1/0
--- - - - - - - - -

..4111 A IB 1 C I D j E G 1
1 ·• 1 -
2 1
IThe formula or function used is dividing by zero or empty c,ells.l
3 1

4 I
lf cell A2 refers to Al with a formula such as =Al *2, then the error propagates through that
formula too:

1 A2
--- v
-
1:1 --- i /x 1 =Al *2

..-.1 A I B C j D E
1 j •t 1·
2 •• '. :.1 ...
3 I [ The formula or function used is dividing by zero or empty cells.]
4 I

The error replaces the value that would have otherwise been calculated. There's no result for
the multiplication in cell A2, only the error from the division in Al.

Power Fx works the same way. In general, if an error is provided as an argument to a function
or operator, the operation won't take place and the input error will flow through as the result
of the operation. For example, Mid( Text( 1/0 ) , 1, 1 ) will return a Division by Zero error, as
the inner most error passes through the Text function and Mid function:

Text v = Jxv Mid( Text( 1/0 ), 1, 1)

Tree view X @ Invalid operation: division by zero. X

Screens Components

1 f) Search

+ + New screen v
El ff' App
v D Screen1

0 Label2

In general, errors don't flow through Power Apps control properties. Let's extend the previous
example with an additional control that displays if the first label's Text property is an error
state:

Text v - fx v IsError( LabeL2. Text )

Tree view X

Screens
-- Components
I@
1 f) Search

+ + New screen v Ov

El ff' App
v D Screen1

!:], 0 Label2

0 Labell
Z:}

lt's fine that errors don't propagate through a control because the system will observe errors
on the input to all control properties. The error won't be lost.
Most functions and operators follow the "error in, error out" rule, but there are some
exceptions. The functions lsError, lsErrorOrBlank, and lfError are designed for working with
errors so they may not return an error even if one is passed into them.

Observing errors
Errors aren't observed until their value is used.

As a result, the lf and Select functions may also not return an error if one is passed in. Consider
the formula If( false, 110, 3 ) . There's a division by zero error present in this formula, but
since the If isn't taking that branch because of the false, Power Fx and Power Apps won't
report an error:

Text v - Jxv If( false, 1/0, 3 )

Tree view X

Screens Components

1 P Search
+ + New screen v
IP App
v D Screen1
El

12! LabelZ

Using the Set function with an error won't report an error at the point the error is placed into
the variable. For example in Power Apps, here's a formula in App.OnStart that places a division
by zero error into the variable x:

OnStart v - Jxv Set( x, 1/0 )

Tree view X

Screens Components

1 fJ Search
+ + New screen v
IP App

D Screen1
El

No error is reported, because x isn't being referenced. However, the moment we add a label
control and set its Text property to x, the error is displayed:
Text v = Jxv X

- Tree view X @ Invalid operation: division by zero. X

Screens Components
I@
1 fJ Search

+ New screen v
El Ef' App

v O Screen1

[J, IZI Labels

Z:>

You can observe errors within a formula with the lfError, lsError, and lsErrorOrBlank functions.
With these functions, you can return an alternate value, take alternate action, or modify the
error before it's observed and reported.

Reporting errors
After an error is observed, the next step is to report the error to the end user.

Unlike Excel, there isn't always a convenient place to show an error result, as the result of a
formula may drive a property such as X and Y coordinates of a control for which there's no
convenient place to show some text. Each Power Fx host controls how errors are ultimately
displayed to the end user and how much control the maker has over this process. In Power
Apps, an error banner is shown and App.OnError is used to control how the error is reported.

lt's important to note that App.OnError can't replace the error in the same way that lfError
can. At the point that App.OnError is executed, the error has already happened, and the result
has propagated through other formulas. App.OnError only controls how the error is reported
to the end user and provides a hook for the maker to log the error if desired.

The scope variables FirstError and AIIErrors provide context information about the error or
errors. This provides information on the kind of error and where the error originated and
where it was observed.

Stopping after an error


Behavior formulas support taking action, modifying databases, and changing state. These
formulas allow more than one action to be done in a sequence using the ; chaining operator
(or ; ; depending on the locale).

In this case, for example, the grid control is showing what is in the T table. Each button select
changes the state in this table with two Patch calls:
OnSelect V = jxv Patch( T, Index( T,1), {Value:Rand()} ); Patch( T, Index(T,2), {Value:Rand()} )

Tree view X

Screens Components
--
I@
+
1+P Search
New screen v

El EP App

v O Screen1

.:;, ) � DataTab!el
0.52038806

0.43197708

[l5I Button1
Z'>

In a chained behavior formula, actions don't stop after the first error. Let's modify our example
to pass an invalid index number in the first Patch call. The second Patch continues on despite
this earlier error. The first error is reported to the end user, and shown as an error in Studio on
the control:

OnSelect V = jxv Patch( T, Index(T,5), {Value:Rand()} ); Patch( T, Index(T,2), {Value:Rand()} )

Tree view X

--
Screens Components
I@
+
1+P Search

New screen v

El EP App

v D Screenl

.:;, ) lsiiJ DataTablel


0.91238365

Button1
0.28702623

Q;l
Z'>

lfError can be used to stop execution after an error. Similar to the lf function, the third
argument to this function provides a place to put actions that should be executed only if
there's no error:

OnSelect jxv IfError( Patch( T, Index(T, 5), {Value: Rand()} ) ,


Error( AllErrors ) ,
Patch( T, Index(T,2), {Value:Rand()}) )
Tree view X

Screens
--
Components E Format text � Remove formatting P Find and replace
I@
+
1+P Search

New screen v

El EP App

.:;,
v D Screenl

) � DataTab!el
0.91238365
?
0.65526422

[l5I Button1
Z'>

lf an error is encountered during one of the iterations of ForAII, the rest of the iterations won't
stop. ForAII is designed to execute each iteration independently, allowing for parallel
execution. When the ForAII is complete, an error will be returned, which contains all the errors
encountered (by examining AIIErrors in lfError or App.OnError).

For example, the following formula will result in ForAII returning two errors (for the division by
zero for Value of 0, twice) and Collection will have three records (for when Value isn't 0): [1,
2, 3] .
Power Fx

Clea r ( Collect ion ) ;


ForAl l ( [ 1 , 0 , 2 , 0 , 3 ] , I f ( 1/Va l u e > 0 , Collect ( Collect ion , Va lue ) ) ) ;

Worki ng with m u lti ple errors


Since a behavior formula can execute more than one action, it can also encounter more than
one error.

By default, the first error is reported to the end user. In this example, both Patch calls will fail,
the second with a division by zero error. Only the first error (about index) is shown to the user:

OnSelect V = Jx v Patc h( T , I ndex ( T , 5), {Val ue : Rand ( ) } ); Pat ch ( T, Index ( T, 1/0) , {Value : Rand ( ) } )

Tree view X The second argument to the ' Index' function must be between 1 and 2, the lower and upper bounds of the table. The upper bound X
@
may be reduced due to the non-delegation limit.
--
Screens Components
I@
1 f) Search

+ + New screen v
[f' App
El
v O Screen1

q. ) !llel DataTable1
0,58335636

0.65 2 1 7269

Qjl Button1

The lfError function and App.OnError can access all the errors encountered with the AIIErrors
scope variable. In this case, we can set this to a global variable and look at both errors
encountered. They appear in the table in the same order in which they were encountered:

OnSelect jx v IfError( Patc h ( T , I ndex (T , 5 ), {Va l u e : Rand ( ) } ) ; Pat c h ( T, Index ( T , 1/0) , {Val u e : Rand ( ) } ) ,
Set ( �atc hErrors , Al lErro rs ) )

Tree view X A PatchErrors Data type: Table


Screens
-- Components
I@ Details Kind Message Observed
1 f) Search

+ +
J
New screen v [Record) 25 The second argu ment to the ' I n d ex' function must be between 1 and 2, . . . Butto n l .OnSelect

[f' App
El [Recordl 13 Invalid operation: division by zero. Buno n l .OnSelect
v O Screen1 1o.s, E Format text � Remove formatting .,P Find and replace
q.
0.6521 7269
) Ilm OataTable1

Qj1 Button1

Multiple errors can be returned in non-behavior formulas too. For example, using the Patch
function with a batch of records to update can return multiple errors, one for each record that
fails.

Errors i n ta bles
As we saw earlier, errors can be stored in variables. Errors can also be included in data
structures, such as tables. This is an important so that an error on any one record can't
invalidate the entire table.

For example, consider this data table control in Power Apps:

em � ------- v l
I lt_
� _ �
= Jx v AddColumn s( [ - 3, 0 , 3 ] , " Rec i p rocal " , 1/Value )

Tree view X

Screens Components

1 JJ Search

+ + New screen v Value Rec1procal

-3 -0.33333333
e EP App
[[e rror]]
v D Screen1 0.33333333

v [ffl DataTablel

Eil Reciprocal_Column 1

Eil Value_Column1

The calculation in AddColumns has encountered a division by zero error for one of the values.
For that one record, the Reciprocal column has an error value (division by zero) but the other
records don't and are fine. I s E rro r ( Index ( output , 2 ) ) returns false and I s E rro r ( Index (
output , 2 ) . Va l u e ) returns true.

lf an error occurs when filtering a table, the entire record is an error but still returned in the
result so that the end user knows something was there and there's a problem.

Take this example. Here, the original table has no errors, but the act of filtering creates an error
whenever Value is equal to 0:

ltems v = jx v F ilte r ( T a ble ( { N : " A " , P : - 5 } , { N: " B " , P : 0} , { N: " C " , P : - 3} , { N : " D " , P : 0} , { N : " E " , P : 5} ) , 1/ P > 0 )

Tree view X

Screens
-- Components
I@
1 P Search

+ + New screen v
• N
• p

[[error]] [[error]]
e EP App
[[error]] [[error]]
v D Screen1 5
q;, v [ffl DataTable1

!iil P_Column2
Z?
Eil N_Co!umn2

The values -5 and -3 are properly filtered out. The values O result in an error in processing the
filter, and so it's unclear if the record should be included or not in the result. To maximize
transparency for end users and help makers debug, we include an error record in place of the
original. In this case, I s E rro r ( I ndex ( output , 2 ) ) returns true.

Data source errors


The functions that modify data in data sources, such as Patch, Collect, Remove, Removelf,
Update, Updatelf, and SubmitForm report errors in two ways:
• Each of these functions will return an error value as the result of the operation. Errors can
be detected with lsError and replaced or suppressed with lfError and App.OnError as
usual.
• After the operation, the Errors function will also return the errors for previous operations.
This can be useful for displaying the error message on a form screen without needing to
capture the error in a state variable.

For example, this formula will check for an error from Collect and display a custom error
message:

Power Fx

IfError( Coll ec t( Nam es, { Nam e : "duplica t e" } ),


No tify( $"00PS : { FirstError.M essag e }", No tifica tionTyp e.Warning))

The Errors function also returns information about past errors during runtime operations. lt
can be useful for displaying an error on a form screen without needing to capture the error in
a state variable.

Rethrowing errors
Sometimes some potential errors are expected and can be safely ignored. Inside lfError and
App.OnError, if an error is detected that should be passed on to the next higher handler, it can
be rethrown with Error( AllErrors).

Creating your own errors


You can also create your own errors with the Error function.

lt you're creating your own errors, it's recommended that you use values above 1000 to avoid
potential conflicts with future system error values.

ErrorKind enu m va l ues


,. �
L J Expand table

ErrorKind enum Value Description

Ana lysisError 18 System error. There was a problem with compiler analysis.

Bad languageCode 14 An i nvalid o r u n recog n ized language code was used.


ErrorKind enum Value Description

Bad Regex 15 I nvalid reg u l a r expression. Check the syntax used with the lsMatch,
Match, or MatchAI I fu nctions.

Confl ict 6 The record being u pdated has a l ready been changed at the sou rce and
the confl ict needs to be resolved. A com mon solution is to save a ny local
changes, refresh the record, and rea pply the changes.

Constrai ntViolated 8 The record did n't pass a constra i nt check on the server.

CreatePermission 3 The user doesn't have create record permission for the data sou rce. For
exa mple, the Collect fu nction was called.

DeletePermissions 5 The user doesn't have delete record permission for the data sou rce. For
exa mple, the Remove fu nction was called.

Div0 13 Division by zero.

EditPerm issions 4 The user doesn't have create record permission for the data sou rce. For
exa mple, the Patch fu nction was called.

GeneratedVa l u e 9 A value was erroneously passed to the server for a field that is
automatica l ly calculated by the server.

l nvalid Fu nction Usage 16 I nvalid usage of a fu nction. Often one or more of the arg u ments to the
fu nction is incorrect or used in a n i nvalid way.

FileNotFound 17 The SaveData storage cou ldn't be found.

l nsufficientMemory 21 There isn't enou g h memory or storage on the device for the operation.

l nval idArg u ment 25 An i nvalid arg u ment was passed to a fu nction.

I nterna! 26 System error. There was a n i nterna l problem with one of the fu nctions.

M issi ngReq u i red 2 A req u i red field of a record was m issi ng.

Network 23 There was a problem with network com m u n ications.

None 0 System error. There's no error.

NotApplicable 27 No value is available. Usefu l to differentiate a blank value that ca n be


treated as a zero in nu merica l calculations from bla n k val u es that should
be flagged as a potential problem if the value is used.

NotFou nd 7 Record cou ldn't be found. For exa m ple, the record to be mod ified in the
Patch fu nction.

NotSu pported 20 Operation not supported by this player or device.


ErrorKind enum Value Description

N u meric 24 A nu meric fu nction was used in an improper way. For exa mple, Sqrt with
-1.

QuoteExceeded 22 Storage quota exceeded.

ReadOn lyValue 10 Col u m n is read only and ca n't be mod ified.

Read Permission 19 The user doesn't have read record permission for the data sou rce.

Sync 1 An error was reported by the data sou rce. Check the M essage col u m n for
more information.

U n known 12 There was a n error, but of a n u n known ki nd.

Validation 11 The record did n't pass a va l idation check.

You might also like