How to use set_default_error_handling?

I’m trying to import set_default_error_handling using the code from the docs custom-error-handling.

I have two questions:

  1. Where should this code be placed? I’m assuming in the server module.
  2. How do I import the function set_default_error_handling?

This code has to be placed on the client-side. And it comes along with all other important functions that are available when calling

from anvil import *

Here is how to use it:


def errorhandler(error):
    #Do whatever you want with the error here
    
set_default_error_handling(errorhandler)

You should probably place it in your startup form/module

1 Like

Your code can also call it again, later, to change how your Client code responds to exceptions, i.e., direct them to a different function.

This might be appropriate, for example, if your App enters a new running phase, with new kinds of exceptions possible, and new strategies for handling them.

In short, you aren’t forced to make a single function handle every phase your App goes through while running.

2 Likes

Ah yes, placing it in the startup module on the client side works. Also, importing using from anvil import * works.

I wonder if there’s a more specific way to import it though. I suppose not importing everything reduces the load times?

import is a Python feature, with tradeoffs either way, whether you’re doing it in Anvil or not. The tradeoffs are documented elsewhere on the Internet, and that’s the best place to look for them.

As I understand it, when you import a module, Python must read and execute the entire module, no matter whether you use a plain import or from ... import .... Overall, the time savings you might have expected doesn’t happen.

The tradeoffs come from the fact that the module you’re importing usually has its own import statements to execute. So the import machinery has to be able to suspend itself, start a whole new import, and finish the suspended imports later.

Kind of mind-boggling. But the tradeoffs derive directly from the consequences. For modules I write, it’s usually best to keep the import itself as simple as possible. That is, import the entire module as-is, e.g.,

import X

X.some_function()

and avoid any kind of shortcut that would let me write somefunction() instead, without the X..

I’ve used the other alternatives, and in some cases by doing so, I created maintenance problems for myself.

1 Like

By the way, you can only include the specific function using

from anvil import set_default_error_handling

Also, you will find that the import statement from anvil import * has been added to all forms and modules by default since it has of the most important functions for anvil (like open_form). If that is the case, you might end up slowing things instead.

I will also point out that anvil imports on the client-side usually happen ‘almost’ instantly. So if you are dealing with a slow app, import statements are usually not the culprits.

1 Like