pythonpandasplotlyplotly-dashdashboard

Return an Error Message in Plotly Dash and place at the top of the page


I have a fairly complex visualization tool I created in Plotly Dash, so I won't share the entire code, though what I am trying to do is return an error message using a try/except block.

except Exception as e:
            print(e)
            return html.Div([
                html.B('THERE WAS AN ERROR PROCESSING THIS FILE - PLEASE REVIEW FORMATTING.')
])     

This works, technically, but I can't find a method to return the message as the first html.Div and therefore at the top of the page. Currently it returns right at the bottom. Anybody tried to address this before?


Solution

  • It is hard to figure out a precise answer with that few information, but assuming that you use @callback functions, I think something like this should work:

    from dash import Dash, html, callback, Input, Output
    
    app = Dash(__name__)
    
    app.layout = html.Div([
        html.Div(
            id='error-div' # your error message will be displayed here, if there is one
        ),
        html.Div(
            id='your-usual-content' # if everythin works, your file gets displayed here or sth like that
        )
    ])
    
    @callback(
        Output('error-div', 'children'),
        Output('your-usual-content', 'children'),
        Input('file-upload', 'contents')) # contents is just a guess here
    def process_file(file):
        try:
            # do something with your file here
            return None, 'Whatever you want to return here, if it worked.' # first return value is for the first Output (id='error-div'), second return value is for the second Output (id='your-usual-content')
        except:
            return html.B('THERE WAS AN ERROR PROCESSING THIS FILE - PLEASE REVIEW FORMATTING.'), ''
    
    if __name__ == '__main__':
        app.run_server()
    

    Basically you can do that error handling within the @callback function you are using (if you do so) and return e.g. a html.Div or anything else to some html.Div you implement into your app.layout. If you don't want a Div to be rendered at all - e.g. because there is no error - you just can return None.