Handling custom exceptions

Silly question but I can’t find the answer.

I’m trying to raise some custom errors from a server module as described here:

I raise the error like
raise MyError(“Oops”)

When I print the exception I receive in the client it looks like:
loginError: Oops on line 51

What are the properties of the exception so that I can break out the error type, string, and location seperately? Or do I have to parse the string?

bump
I’m still looking for more information about handling errors.

When you catch the exception, you can cast it to a string, and get its type using type"

try:
  raise ValueError("oops, a value was incorrect")
except ValueError as exc:
  print(exc)
  print(type(exc)) 

Accessing the entire traceback programmatically is currently not supported.

You can override the default error handler using set_default_error_handling:

# This code displays an Anvil alert, rather than
# the default red box, when an error occurs.

def error_handler(err):
  alert(str(err), title="An error has occurred")

set_default_error_handling(error_handler)

See here in the docs.

Thanks shaun but I don’t think I was clear.
When I raise a custom error on the server and pass it a string, the error I catch on the client is a modified string. Anvil has changed it by concatenating the type and location.

I assume the custom error which is derived from AnvilWrappedError has properties that include the unmodified string but since pprint isn’t implemented on the client, I can’t easily dump its structure.

I can’t find documentation about the properties of AnvilWrappedError

I haven’t tried it much on the client, but the standard Python dir() function might possibly be of use, e.g., dir(err) ?

1 Like

You can get the original message using the .message attribute:

    try:
      anvil.server.call('raise_exception')
    except anvil.server.AnvilWrappedError as exc:
      print(exc)
      print(exc.message)

I haven’t tried it much on the client, but the standard Python dir() function might possibly be of use, e.g., dir(err) ?

Always a good tip! Python is amazing at introspection, it’s one of the things that made me fall in love with it :slight_smile:

1 Like