✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

How to create 404 error page in Dash?

In Flask I can genegate 404 (https://flask.palletsprojects.com/en/1.1.x/errorhandling/):

@app.errorhandler(404)
def page_not_found(error):
	output = render_template("404.html",
							 title = 'Page not found')

but how do it in Dash?

Hello, I am trying to figure out how to do this now. Did you by chance figure out how to get this to work in Dash? If anyone could shed some light on this or if it is even possible to do in Dash, that would be very helpful.

If you are using Dash’s dcc.Location component, then return your own components with a 404 message within the callback that returns children based off of the href. This would be within the “else” conditional statement that matches hrefs.

https://dash.plotly.com/urls

Is there any way to do this and still return a 404 code?

There isn’t. If you needed the 404 code, then adding your own URL router with flask might be the way to go.

I used the following code to generate a dynamic error message page, which includes 404. It passes along the error code, the name of the error, and a description of the error.

from werkzeug.exceptions import HTTPException, InternalServerError

# This generates a dynamic HTTP exception page
@app.server.errorhandler(HTTPException)
def handle_http_exception(e):
    return render_template("http_exception.html", code=e.code, name=e.name, description=e.description)

# This responds with an internal server error page
@app.server.errorhandler(InternalServerError)
def handle_internal_server_error(e):
    return render_template("http_exception.html", code=e.code, name=e.name, description=e.description)

Then, I created a ‘templates’ folder in the same directory as my python application (.py). Within that folder is a file called ‘http_exception.html’ with the following contents:

<html>
   <head>
      <title>{{ code }} - {{ name }}</title>
   </head>
   <body>
      <br /><br /><br /><br />
      <table width='100%'>
         <tr>
            <td align='center'>
               <p><font size="5" color="red">{{ code }} - {{ name }}</<br /><br /></font><br />
                  <b>{{ description }}</b>
               </p>
      </table>
   </body>
</html>

Here’s an example screenshot:

1 Like