Handle 404 throw by code in appengine

I manage the "real" 404 errors this way:

application = webapp.WSGIApplication([
     ('/', MainPage),    
     #Some others urls
     ('/.*',Trow404) #I got the 404 page
],debug=False)

But in some parts of my code, I throw a 404 error

self.error(404)

and I want to show the same page that I mentioned earlier - is there a way to catch the 404 error and manage it?

I can redirect to some non-existent url but it looks ugly

+5
source share
2 answers

The easiest way to do this is to override the error () method on your base handler (suppose you have one) to create a 404 page and call it from your regular handlers and your 404 handler. For example:

class BaseHandler(webapp.RequestHandler):
  def error(self, code):
    super(BaseHandler, self).error(code)
    if code == 404:
      # Output 404 page

class MyHandler(BaseHandler):
  def get(self, some_id):
    some_obj = SomeModel.get_by_id(some_id)
    if not some_obj:
      self.error(404)
      return
    # ...

class Error404Handler(BaseHandler):
  def get(self):
    self.error(404)
+9
source

Piggy Derek Dahmer ( , ), Throw404, :

class Throw404(webapp.RequestHandler):
  def get(self):
    self.error(404)
    # your 404 handler goes here
0

All Articles