Power Apps OnError Property: Capture & Log Unexpected Errors
Power Apps OnError Property: Capture & Log Unexpected Errors Posted by - Matthew Devaney on - May 1, 2022 23 Comments As an app developer I try to anticipate...
- Published
- Reading time
- 10 min read
Before you start
Is this guide for you?
- Best entry point
- Power Apps
- Time investment
- 10 min read
Imported reference from Matthew Devaney's blog for learning purposes. Original: https://www.matthewdevaney.com/power-apps-onerror-property-capture-log-unexpected-errors/. Author: Matthew Devaney.
Power Apps OnError Property: Capture & Log Unexpected Errors Posted by - Matthew Devaney on - May 1, 2022 23 Comments
As an app developer I try to anticipate any possible errors the user could get and tell the app what to do when that error happens. But I can’t anticipate every possible scenario, so what should I do in those cases? With Power Apps OnError property we can tell the app to display a custom message for any unhandled errors, send details to the app monitor and record the errors in a log file for the developers to take a look at later.
In this tutorial I will explain the new Power Apps OnError Property and show your best way to deal with unhandled errors. Table of Contents
Introduction: The Currency Exchange Calculator App
Enable The Formula-Level Error Management Setting
Create A New Canvas App In Power Apps Studio Calculate The Currency Exchange Rate
Generate An Unhandled Error In Power Apps
Write A Custom Error Message With Power Apps OnError Property
Send Error Details To Power Apps Monitor
Track Unhandled Power Apps Errors In Application Insights
Link The Power Apps App To Application Insights
Get A Report Of All Power Apps Errors In Application Insights List Of Power Apps Error Kind Codes
Introduction: The Currency Exchange Calculator App
The Currency Exchange Calculator App is used by employees at a travel agency to check the current rates for clients. When an employee inputs an invalid value into the app they see an error message on the screen and the error details are silently logged to a database for the application development team to review.
Enable The Formula-Level Error Management Setting
The new Power Apps OnError property is still in experimental mode. To use this new feature open Power Apps Studio and create a new canvas app from blank. Then go to File > Settings > Upcoming features > Experimental and turn on Formula-level error management.
Also make sure that the Power Apps Authoring version is 3.21122 or greater.
Create A New Canvas App In Power Apps Studio
In our newly created canvas app, insert a label with the text “Currency Exchange Calculator” at the top of the screen.
Next, place a button onto the screen. We will change its style to look like a card and then position several other controls on top of it.
Use these settings in the following properties of the button. BorderRadiusBottomLeft : 10 BorderRadiusBottomRight : 10 BorderRadiusTopLeft : 10 BorderRadiusTopRight : 10 DisabledBorderColor : DarkGray DisplayMode : DisplayModel.Disabled Fill : White Code language: HTTP ( http )
Then create three pairings of labels and text inputs as shown in the image below and place a button at the bottom: Euro Dollars Exchange Rate US Dollars Calculate The Currency Exchange Rate
With basic design of our app completed, next we will add some code to calculate the currency exchange rate. Our goal is to generate an error message using Power Apps OnError Property so we will intentionally make a mistake. Select the Euro Dollars text input and change the Format property to Text. This is wrong because only numbers should be written in the text input.
Then write the value 1.05 in the Default property of the Exchange Rate text input. This is a hardcoded value but if we were making a real app the exchange rate would be filled-in from an online service or some other datasource.
When the Convert button is clicked it will multiply the amount of Euro Dollars by the exchange rate and store the result in a variable.
Use this code in the OnSelect property of the Convert button. Set ( varResult , Value ( txt_Calculator_EuroDollars
.Text ) * Value ( txt_Calculator_ExchangeRate .Text ) ); Reset ( txt_Calculator_USDollars ) Code language: CSS ( css )
The result of the currency exchange calculation should be displayed in the US Dollars text input.
Use this code in the Default property of the US Dollars text input. varResult Generate An Unhandled Error In Power Apps
Our goal was to create an app that would generate an error message. Now we have the ability to do that. Write the letters “ABC” in the Euro Dollars text input and click the Convert button. When we do this Power Apps will display an error message that says “Invalid arguments to the Value function”. The Value function converts a text string to a number. An error occurs because ABC cannot be converted to a number.
The error that we generated is considered an unhandled error . When an unhandled error occurs Power Apps checks the OnError property for what actions to take next, usually, display a custom error message and trace the error details. Right now we do not have and logic written in Power Apps OnError property so it displays a generic error message by default.
A handled error is one that the developer anticipated in advance and wrote specific logic in an
IfError function to tell Power Apps what should happen next. For example, we could have written our button’s On Select button code like this. The 1st argument to IfError is a set of code Power Apps should try to execute. If that code fails for any reason Power Apps will run the code in IfError’s 2nd argument.
IMPORTANT: Do not change the button’s OnSelect code to use IfError. The rest of this tutorial will not work if you do this. <meta charset= "utf-8" >IfError(
Set ( varResult, Value(txt_Calculator_EuroDollars.Text) * Value(txt_Calculator_ExchangeRate.Text) ); Reset(txt_Calculator_USDollars), Notify(
"An error occurred: " & FirstError.Message, NotificationType.Error ) ); Code language: JavaScript ( javascript )
Write A Custom Error Message With Power Apps OnError Property
When an unhandled error happens we should use Power Apps OnError property to give a detailed error message that will allow the developer to debug the app.
Write this code in the OnError property of the app. It will display a banner at the top of the screen with an error message, the name of the control where the error was observed and the the name of the control where the error initially occurred. FirstError is a special method that can only be used inside the IfError function or the OnError property. For more information on FirstError go read the official documentation . Notify ( Concatenate ( FirstError .Message , ", Observed : ", FirstError .Observed , ", Source : ", FirstError .Source ), NotificationType .Error ); Code language: CSS ( css )
Now when we click the Convert button a more helpful error message is shown.
Send Error Details To Power Apps Monitor
Power Apps monitor is a tool developers can use to see all of the activity in a user’s session and debug their apps. Error messages logged by Power Apps monitor do not have much detail by default. We can create our own custom logging with the Trace function to include all the information needed to diagnose and fix a problem
Add the Trace function code to the OnError property of the app. Notice that we are now tracking 6 pieces of information when an error occurs: error kind, error message, the control where the error was observed, the screen the user was on, the control that was the source of the error and user email.
<meta charset= "utf-8" >Notify( Concatenate( FirstError.Message, ", Observed: " , FirstError.Observed,
", Source: " , FirstError.Source ), NotificationType.Error ); Trace(
"Unhandled Error" , TraceSeverity.Error, { Kind : FirstError.Kind, Message : FirstError.Message, Observed : FirstError.Observed, Screen : App.ActiveScreen.Name, Source : FirstError.Source, User : User().Email } ) Code language: JavaScript ( javascript )
Open Power Apps Monitor from the Advanced Tools menu.
Then generate the error message again and watch it appear in Power Apps monitor. On line 3 of the screenshot below we can see the result of our Trace function.
If we drill-into the details of the error we can see the additional information added by the trace.
Track Unhandled Power Apps Errors In Application Insights
As a developer, wouldn’t it be useful to know what errors your users are receiving so you can fix them? Most bugs that happen never get reported. But did if we know what errors were happening then we could do something about it and continuously improve the user experience.
Azure Application Insights can be used to log all of the errors captured by Power Apps Trace function . It’s simple to setup and cheap to use – often only a few pennies on your organization’s Azure bill.
Go to portal.azure.com and open the Application Insights service. Create a new application.
Choose a resource group and give your application a name. I suggest using the name of your app with _PowerApps at the end to make it easily identifiable. Click Review + Create once setup is finished. Then click Create on the next screen.
Link The Power Apps App To Application Insights
Now that we’ve create a new app in Application Insights we must link it to our app in Power Apps. Go to the Overview section of the app and copy the Instrumentation Key.
Then go back to Power Apps, select the app object, open the right-menu and paste the Instrumentation Key into the field shown below. Save and publish the app.
IMPORTANT: the app will not become linked to Application Insights until you save and publish the app
Get A Report Of All Power Apps Errors In Application Insights
Any errors captured by Power Apps trace function can be viewed in Application Insights. Select Logs from the left-menu of Application Insights.
Then write a query to retrieve all of the traces.
Copy and paste this code into the query editor and click the Run button. Notice that the text “Unhandled Error” is exactly the same as what we placed in our Power Apps trace function.
traces | where message == "Unhandled Error" Code language: JavaScript ( javascript )
All of the error messages will be displayed in the results field and we can drill-down into them to get detailed reporting. We can export these errors to a CSV file, open them in an Excel spreadsheet or even send them to Power BI!
IMPORTANT: the trace function result will only be logged work while the app is in Play Mode . No traces will be sent during preview mode in Power Apps Studio. List Of Power Apps Error Kind Codes
As part of our error logging we included the error kind. The error kind is a numeric error code but here is not any documentation on what they mean. I have provided a table of all error kind values and their meanings in the table below. ErrorKind Value None 0 Sync 1 MissingRequired 2 CreatePermission 3 EditPermissions 4 DeletePermissions 5 Conflict 6 NotFound 7 ConstraintViolated 8 GeneratedValue 9 ReadOnlyValue 10 Validation 11 Unknown 12 Div0 13 BadLanguageCode 14 BadRegex 15 InvalidFunctionUsage 16 FileNotFound 17 AnalysisError 18 ReadPermission 19 NotSupported 20 InsufficientMemory 21 QuotaExceeded 22 Network 23 Numeric 24 InvalidArgument 25 Internal 26 Did You Enjoy This Article? 😺
Subscribe to get new Copilot Studio articles sent to your inbox each week for FREE Enter your email address Sign Me Up Questions?
If you have any questions about Power Apps OnError Property: Capture & Log Unexpected Errors please leave a message in the comments section below. You can post using your email address and are not required to create an account to join the discussion. Application Insights Error Handling OnError Property Power Apps Monitor Matthew Devaney M365 Copilot Power Apps
How To Create Copilot Custom UI Widgets In Power Apps
Tagged
Power Apps
Have a Microsoft 365 topic idea?
Share article suggestions, community session ideas, corrections, or real-world scenarios for future nxtM365 learning notes.
Keep learning Microsoft 365
Explore more practical guides for SharePoint, Power Platform, Copilot Studio, migration, automation, governance, and security.
Continue learning
Related tutorials
Related questions
Related comparisons
Next action