Vue normale

Il y a de nouveaux articles disponibles, cliquez pour rafraîchir la page.
À partir d’avant-hierFlux principal

The easiest way to test how your app handles API errors

The easiest way to test how your app handles API errors

How would you test this code?

async function getData() {
  try {
    const result = await fetch('https://contoso.com/api/data');
    if (result.ok) {
      return await result.json();
    }
  }
  catch (e) {
    // handle API errors here
  }
}

More specifically, how would you verify that the code in the catch clause, responsible for handling errors is working properly?

What if your API-handling code is more elaborate? What if you want to use rate limiting headers to back off and avoid getting throttled? And when you get throttled, you want to wait for the designated period and retry the request automatically? How do you verify that your code works correctly?

Using APIs is hard

It's hard to imagine an app that's not connected to an API these days. We use APIs for everything: from authentication, to data storage, to integrating AI. APIs are literally everywhere. And yet, it's surprising to see how hard it still is to build robust apps that use APIs.

The APIs we use in our apps are built by different vendors. Each API works differently than the other. But that's fine. Using their docs, we can integrate these APIs in our apps just fine. We can even go as far as to automate testing different scenarios relevant to our app. But not all of them.

While it's easy to get APIs to work, it's hard to break them. Yes, you can easily send an invalid request and see it respond with an error, but that's hardly something you'd see in production, unless you missed something fundamental. What is really hard about working with APIs is simulating different error states, like rate limits, throttling or servers getting overloaded.

What makes it even harder, is that vendors who publish APIs, often spend more time in their docs communicating how their APIs work rather than how their APIs behave when they fail. "It's a matter of perception" - you could say. But if you've worked with APIs a bit, you know that API failure is not a matter of "if" but "when". And having proper docs that describe erroneous behavior makes all the difference.

How developers handle API errors

Handling API errors is hard. Here's how developers typically deal with it.

Wrap the whole request in a try..catch

Probably the most frequently used solution out there is to wrap the whole web request in a try..catch clause. If calling an API fails for whatever reason, the app catches the error and shows a generic error. I bet you've seen an error similar to An error has occurred. Reload the page more than once. This is exactly, because developers used a generic try..catch statement.

Using this approach gives you an easy way out. After all, as a developer, you don't have to care about the exact API error. Something went wrong in an API you don't own, so you can't do nothing about it, right? So you show a generic error to the user, asking them to retry. What else can you do, right?

Use a dependency

There are dependencies that you can use in your project to help you handle API errors. Their functionality can be as simple as handling basic OData errors to handling throttling with exponential back offs. Thanks to these dependencies you can be smarter and automatically recover when possible without bother the user.

While it sounds great, what makes you so sure that the dependency will work properly with the APIs that you use in your app? Have you actually checked it? How would you though?

Make the API fail

When developers want to see how their app behaves when it gets throttled, they sometimes overload the API on purpose. They'll keep calling it until they exceed the quota or force a server error due to too high resource consumption.

It's far from perfect for both the API vendor and the developers. API vendor loses precious resources sometimes even leading to service outage, and developers incur additional costs. But how else would you verify how the app actually behaves when it gets one of these elusive errors?

Simulate API errors with mocks

More experienced developers, especially when they build a product, might go as far as mock APIs they use. Rather than calling the actual API, they simulate API responses in code what allows them to test different edge cases. This isn't trivial to do.

First, you need to have a thorough understanding of the API that you're using and its different behaviors. Can you get throttled? Does the API communicate rating limits? What other error states could the API communicate that you should consider? When do these errors occur and what is the shape of the error response that your app gets?

Once you know all of this, then you need to setup the necessary infrastructure to mock API calls and simulate the different errors. Simulating simple errors isn't hard. But it gets complicated when you get to simulating more complex behaviors like rate limiting that spans a series of requests.

And after you figured it all out, you also need to keep this in sync with the actual behaviors of the APIs that you use in your app.

Using APIs properly is hard

There's more to using APIs than meets the eye. A 200 OK response is just the tip of the iceberg. If you want to build robust apps that use APIs, you need to properly handle possible errors, and you have to verify that you're doing it correctly. This has nothing to do with your app's functionality, but what's the alternative? Hoping for the best while knowing that it's just a matter of time until your app breaks and loses someone's work?

See for yourself how your app will behave when APIs fail

The good news is, that there's a better way for you to see how your app will behave when the APIs that it uses fail. It allows you to see not just regular API failures, but rate limiting, throttling and any other type of error that an API might return. And you can do it without changing a single line of code in your app or standing up specific testing infrastructure and elaborate tests. Here's how.

Microsoft Graph Developer Proxy - an open-source proxy from Microsoft, allows you to simulate API errors. When you start it on your developer machine, it intercepts web requests from your app and returns simulated errors. You can use the Developer Proxy for simulating simple errors and more complex behaviors like throttling on any API. And because it's a proxy, you can use it with any type of app, build on any technology stack.

Check out this single-page app connected to Microsoft Graph that shows you information about people. At first, it seems to work just fine:

Web application showing photos and names of people

Let's see what happens, when one of the API calls would fail:

Empty page in a web browser. Next to it, a terminal window with Microsoft Graph Developer Proxy simulating API errors

Because the developer didn't implement any error handling, as soon as an API call failed, the whole app failed leaving the user with an empty screen. And remember what we discussed: it's just a matter of time before calling an API fails, so you better be prepared for it.

See how quickly we were able to find a flaw in this app? Notice, that we didn't have to change anything about the app or stand up any testing infrastructure. All we did was start the Developer Proxy and run the app. That's it.

Using the Developer Proxy, you'll find all kinds of issues related to using APIs in your apps:

  • How does your app behave when calling an API fails? Can it handle the error gracefully or will it crash losing the user's work?
  • Is the error message that you show to the user relevant to the type of error that occurred?
  • Do you even need to show an error message to the user or can you automatically recover, for example by retrying the failed request after some time?
  • When loading data takes longer than expected, is it clear to the user that your app is still working?
  • Could you cache data to use as fallback in case calling the API fails?

These are just some examples of insights about your app that you'll get when you test it with Microsoft Graph Developer Proxy.

Building robust apps that use APIs doesn't have to be hard. Microsoft Graph Developer Proxy allows you to see for yourself how your app will behave when calling APIs that it uses fails. With Microsoft Graph Developer Proxy, you can test any kind of app, using any API. Break your app on your box, handle errors gracefully and deploy your app to production with confidence. Your customers will thank you.

Get started at https://aka.ms/graph/proxy.

Comment l’A/B Testing peut aider à améliorer le taux de conversion d’un e-commerce ?

Pour toute boutique en ligne, la mesure ultime du succès est le taux de conversion. Cette métrique est essentielle pour évaluer l’efficacité de la conception, de la mise en page et de l’expérience client globale de la boutique. Comprendre comment augmenter ce taux est un défi permanent pour les détaillants en ligne, et les tests A/B peuvent être un outil précieux. Le test A/B est une méthode qui consiste à comparer deux versions d’une page Web ou d’une campagne d’emailing afin de déterminer laquelle est la plus performante. En effectuant plusieurs tests, le test A/B peut aider les propriétaires d’e-commerce à identifier les éléments de leur boutique auxquels les clients réagissent et à créer une expérience d’achat en ligne plus réussie. Dans ce billet de blog, nous allons explorer comment les tests A/B peuvent être utilisés pour optimiser le taux de conversion de ta boutique et proposer des stratégies pour tirer le meilleur parti de cet outil puissant.

Définis les objectifs de ton test A/B

La première étape de tout test A/B efficace consiste à définir clairement les objectifs que tu espères atteindre. Quels éléments de ta boutique cherches-tu à optimiser ? Quels changements spécifiques veux-tu mesurer ? Connaître les réponses à ces questions t’aidera à identifier les zones de ta boutique sur lesquelles te concentrer, ainsi que la façon de concevoir tes tests A/B. Si tu n’es pas sûre de tes objectifs, parle à un spécialiste ou consulte une analyse de marché pour déterminer le type de changements à apporter. Une fois que tu as bien compris les objectifs, tu peux passer à la conception et à l’exécution de tes tests A/B.

Établis des indicateurs de performance clés

Après avoir défini tes objectifs, l’étape suivante consiste à établir des indicateurs de performance clés (KPI) pour mesurer le succès de tes tests A/B. Tes IRC doivent être spécifiques, mesurables et exploitables. Voici quelques exemples d’IRC : le nombre total de visites sur le site Web, les pages vues, le taux de rebond, le temps passé sur la page, la valeur moyenne des commandes et le taux de conversion. Une fois que tu as établi ces IRC, tu peux les utiliser pour t’aider à prendre des décisions et à mesurer le succès de tes tests A/B. Assure-toi de suivre ces IRC avant et après chaque test pour pouvoir voir comment les changements que tu fais ont un impact sur les performances de ta boutique.

Mets en place le test A/B

Le test A/B est la pratique qui consiste à tester deux versions d’une page Web ou d’une application pour déterminer laquelle est la plus performante. C’est un excellent moyen d’optimiser le taux de conversion de ta boutique et de maximiser tes bénéfices. En testant deux versions d’une page, tu peux rapidement déterminer quelle version est la plus efficace pour convertir les visiteurs en clients. Cela te permet de prendre des décisions basées sur des données pour savoir quelle version de ta boutique fonctionne le mieux. Le test A/B est un moyen simple mais puissant d’optimiser ta boutique et d’augmenter tes ventes.

Analyse les données

Après avoir effectué tes tests A/B, il est maintenant temps d’analyser les données. C’est l’une des étapes les plus importantes du processus, car elle te permettra de savoir ce qui a marché et ce qui n’a pas marché. Il est important d’examiner les données d’un point de vue qualitatif et quantitatif. Regarde les chiffres réels et compare-les aux objectifs que tu as fixés pour ton test. Prends aussi en compte les commentaires qualitatifs des clients, comme la facilité à trouver des articles sur la page ou l’utilité des descriptions de produits. En prenant en compte les données quantitatives et qualitatives, tu peux t’assurer que tu optimises le taux de conversion de ta boutique et que tu offres la meilleure expérience client possible.

Crée plusieurs versions de ton site Web

L’une des meilleures façons d’optimiser le taux de conversion de ta boutique est de créer plusieurs versions de ton site Web. Le test A/B est une méthode qui consiste à comparer deux versions d’un site Web pour voir laquelle est la plus performante. Tu peux tester différents éléments de ton site Web, comme la mise en page, le texte, les images et même le jeu de couleurs. En testant différentes versions de ton site Web, tu peux déterminer la version à laquelle tes clients réagissent le mieux, et apporter des modifications en conséquence. Cela t’aidera à maximiser le taux de conversion de ta boutique et à augmenter tes ventes.

Surveille tes résultats

La sixième et dernière étape de tout processus de test A/B réussi consiste à surveiller tes résultats. Cela implique de collecter des données sur la façon dont les clients interagissent avec les différentes versions de ta boutique et de les analyser pour voir laquelle fonctionne le mieux. Tu dois aussi vérifier périodiquement comment les performances de chaque version évoluent au fil du temps. En faisant cela, tu peux apporter des ajustements à ta boutique si nécessaire pour maximiser son taux de conversion.

Ajuste ton site Web en fonction des résultats

Une fois que tu as collecté les données de ton test A/B, il est temps de faire les ajustements nécessaires. Tu dois ajuster ton site Web en fonction des résultats du test afin d’optimiser le taux de conversion de ta boutique. Tes changements doivent être mis en œuvre en temps voulu pour que tes visiteurs bénéficient de la meilleure expérience possible. Il peut s’agir de modifier la mise en page de ta page, de faciliter le processus de paiement ou d’inclure un contenu plus visuel. Après avoir apporté les changements, tu devrais effectuer un autre test pour voir si cela a eu un effet sur ton taux de conversion.

Répète le processus pour optimiser davantage ton site Web

Une fois que tu as testé ton site Web et analysé les résultats de ton test A/B, tu devrais répéter le processus. Cela peut t’aider à optimiser davantage ton site Web en t’assurant que tes changements fonctionnent comme prévu. Le fait d’avoir plusieurs séries de tests A/B peut aussi révéler des informations supplémentaires qui auraient pu être manquées lors des premiers tests, ce qui te permettra de prendre des décisions encore plus éclairées sur la façon d’améliorer le taux de conversion de ton site Web.

En conclusion, les tests A/B sont un outil inestimable pour toute boutique e-commerce qui souhaite optimiser son taux de conversion et augmenter ses ventes. En analysant le comportement des utilisateurs, tu peux prendre des décisions basées sur des données qui auront un impact direct sur tes résultats. Les tests A/B peuvent t’aider à comprendre quelles fonctionnalités les clients préfèrent, quel type de contenu ils engagent et comment ils réagissent à différents éléments de conception. Une fois que tu as ces informations, tu peux apporter des ajustements à ta boutique pour qu’elle plaise à ton public cible et maximise les ventes.

Choisis le bon outil pour faire de l’a/b testing

Comme tu l’as compris, faire de l’a/b testing est finalement assez facile, à partir du moment où tu suis des étapes assez claires et précises ! En revanche, il n’est pas rare de voir certains éditeurs de sites et des équipes marketing être mises à mal face à des outils qui ont une très mauvaise conception… Si, dans votre équipe, vous vous demandez encore pourquoi mettre en place de l’a/b testing sur votre site, cela pourrait même vous pousser à abandonner votre projet !

Pourtant, comme tu le comprends, faire de l’a/b testing peut avoir un impact assez positif sur ton business ! Pour ne pas être déçu, en plus des étapes que j’ai pu te donner dans cet article, je te conseille vraiment de faire un bref comparatif des différentes solutions qui existent pour faire de l’a/b testing. D’ailleurs, fais bien attention ! En effet, il est assez fréquent de voir certaines solutions d’a/b testing se lancer sur le marché, quand d’autres disparaissent complètement ou se font racheter. Sans une étude préalable comme celle-ci, tu pourrais passer à côté d’une très belle opportunité pour booster ton site web !

L’article Comment l’A/B Testing peut aider à améliorer le taux de conversion d’un e-commerce ? est apparu en premier sur Constantin Boulanger.

Tip For Testing Your Flows In Power Automate

Wouldn't it be nice if we can Test our Flows without executing some of the actions like Sending Emails, creating items in SharePoint or Dataverse? Guess what we can! And its very easy to do. Check this out!

BlogPic

jcook127001

Testing Power Apps with Role-Based Security

When we build apps (or applications before them), we often build different behaviors or capabilities based on the role of the current user. For example, when I ask for some time off, my manager can approve it, but I can’t.

In a Power App, there are many different ways to implement role-based permissions. I’ve put a few articles into the Resources below showing some approaches.

See the source image

Testing the Power App by playing the different roles can be very hard. Each user who loads the Power App is themselves, right?

Well, here’s a trick I’ve been using to make things much easier for testing.

Here are the high level steps:

  • Set up the roles using whatever mechanisms you choose. As a SharePoint guy, I like to use lists wherever possible so it’s easy to maintain the roles over time.
  • In your Power App’s initial screen, set up logic to determine the current user and set variables to reflect that user’s role(s) at an app level. (You’re likely to have additional roles when you get deeper into the app, perhaps working with specific items. This approach works there, too!)
  • Add a Combo box to the screen which allows you to select any user.
  • Switch the current user to the “assumed user” when you want to test with that user and their role(s).

Determining the current user is easy: we just use the User() function. But the User() function isn’t really complete enough. I always then define a second variable for currentUser by getting their Office365Users.UserProfile. This requires the Office365Users connector.

When I create a new Power App, one of the first things I do is add these lines to the OnVisible property of the initial landing screen:

// User 
Set(thisUser, User());
Set(currentUser, Office365Users.UserProfile(thisUser.Email));

Between User() and Office365Users.UserProfile, this tells me most of the base information Microsoft 365 knows about the user. Yes, I could use Office365Users.MyProfile() to get the user’s profile information, but then this testing trick wouldn’t work. By using Office365Users.UserProfile and passing in an email address, I can get anyone’s user profile.

Add a Combo box to the screen and rename it to ComboBox_AssumePerson.

Set the Items for ComboBox_AssumePerson to:

Office365Users.SearchUser({searchTerm:ComboBox_AssumePerson.SearchText,top:10}) 

For the OnChange property, add code similar to the following. Here, I’m setting two variables to the selected user from ComboBox_AssumePerson: assumeUser and the currentUser we’ve already defined.

Set(assumeUser, ComboBox_AssumePerson.Selected);
Set(currentUser, ComboBox_AssumePerson.Selected);
Set(returnToLanding, true);
Navigate(PermissionCheck, ScreenTransition.Cover); 

Because of the way we’ve set up the Items for ComboBox_AssumePerson, on selection, we get an object which is equivalent to our call to Office365Users.UserProfile: same type of object, with the same properties.

Now change the last line in the // User code above to assume the selected user if there is one.

Set(currentUser, If(IsBlank(assumeUser), Office365Users.UserProfile(thisUser.Email), assumeUser));

Because I’m setting all the role information in the OnVisible property for the landing screen, just changing the currentUser isn’t enough. To make the change “stick”, I’m navigating to another screen called PermissionCheck which looks at the returnToLanding value in its OnVisible property, and if it it set to true, it navigates right back. That means the role-based calculations all happen again, but this time in the context of assumeUser.

If(returnToLanding, Set(returnToLanding, false); Back()); 

By the way, that PermissionCheck screen can be really handy, too. The only thing going on in that screen is to show the current user’s roles. I tend to set variables like isAdmin, isManager, isExecutive, or isContactTracer on the landing screen. The PermissionCheck screen shows me those values for the current or assumed user whenever I need to be sure what they are. It doesn’t need to be pretty, but by displaying your role-based variables, you have an easy way to check your logic.

Now you can wander around your Power App as the user you have selected and the permissions you have determined for that user.

How do we undo that user assumption? We simply clear the ComboBox_AssumePerson, which fires its OnChange property. Then this line from above sets things back to the real user who is using the Power App because assumeUser no longer has a value.

Set(currentUser, If(IsBlank(assumeUser), Office365Users.UserProfile(thisUser.Email), assumeUser));

Caveats

As with most things, there are some very clear caveats to this approach.

  • When you assume another user’s identity in the app, you’re still you beneath the covers. That means any items created in lists will still be created by you. You’re only able to assume the other user’s identity in the Power App itself.
  • Everywhere you figure out the user’s roles, be sure to use currentUser.Mail – NOT thisUser.Email – to match users from your permission structures. There’s an example of this in my previous post Power Apps: Filtering by Multi-select SharePoint Columns, where I check the user in Section 3.
  • Be sure you have some indication on your screens showing who you are while you’re running the Power App. I think this is a good practice, anyway, but it’s especially important when you have this capability set up. (Who am I again?) I usually have something like this in the upper right of every screen.
  • Some logic may not work with this approach. For example, I can display the User()‘s photo, but not the currentUser‘s.
  • For debugging – even after you launch the Power App for production use – you may want to leave this “back door” in place. But be sure to set the Visible property for ComboBox_AssumePerson so only someone in a role you consider an admin can use it. And make sure they understand it!

Resources

❌
❌