Anvil Extras Authorisation Error Handling

I am trying to display an error message when a user has a failed authorization.

Client Side:

      try:
        self.tabulator.data = anvil.server.call(tabular_server_calls[_type])
      except ValueError as ve:
        error_label = Label(text=str(ve),foreground="#ff0000")      
        self.column_panel_content.add_component(error_label)    

Server Side:

@authenticated_callable
@authorisation_required("permission")
def tabular_server_call():
   """do stuff here"""

Here is the error message:

ValueError: Authorisation required
at anvil_extras/authorisation.py:52

I have tested it withouth the @authenticated_callable and with a permission that does exist and it works. I am just failing to handle the ValueError exception. Should I handle it on the server side? if so, where would the try/except go?

Thank you for reading!

@lsaenz9104 since this is an Anvil Extras question, I would suggest asking about it on the Anvil Extras GitHub page (Discussions · anvilistas/anvil-extras · GitHub) :slight_smile:

2 Likes

The issue was that the error was being raised in the decorator, which is in untouchable code. This did not allow me to catch the exception being raised by an try/except clause.

I resolved this by creating a wrapper function to call the method which has the authorisation_required exception and then returning that exception to the server side:

Additional Code

@authenticated_callable
def tabular_server_call(_id=None):
  try:
    return tabular_server_call_inner(_id=_id)
  except ValueError as e:
    print(f'Exception: {e}')
    return str(e)

@authorisation_required("permission")
def tabular_server_call_inner():
   """do stuff here"""

This allows me to catch the exception I want and pass it to the client side.

Normally you would handle these sorts of exceptions on the client side by wrapping the anvil.server.call line in a try/except block.

That was what I originally tried, but what happened was the error being raised on the server side and preventing the try/except clause to complete on the client side

Odd, I would have expected that to work. You should post about it in the Github link Patricia posted, to let the Anvil Extras folks can see if it’s something specific to them.

1 Like

After posting on the github discussion (thank you @patricia for the suggestion), it looks like I was using the wrong exception. I needed to use except Exception vs except ValueError.

I was trying to be more specific with my exception case as ValueError is the exception raised by anvil extras, but in this situation I’ll take it!

Here’s a link to a more detailed discussion:

2 Likes