views:

378

answers:

3

I manage the "real" 404 errors in 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 wanna show the same page that mentioned before, ¿there is any way to catch the 404 error and manage it?

I can redirect to some inexistent url, but looks ugly

A: 

The simplest solution would be to make a specific URL for 404's and redirect when you want to 'return' a 404 page.

application = webapp.WSGIApplication([
     ('/', MainPage),    
     ('/404/',Throw404), # Here's a page specifically for 404's.
     ('/.*',Throw404) #I got the 404 page
],debug=False)

using this command in your handlers.

self.redirect("/404/")

Note that this doesn't actually return a 404 response code, but will display your custom 'page not found' page, which is seems like you are trying to do.

Derek Dahmer
This seems like a bad idea, since it tells the requesting user agent that a page it didn't request doesn't exist.
Wooble
Sending redirects for 404s is a terrible idea. I wish sites wouldn't do it.
Nick Johnson
A: 

Piggy backing on Derek Dahmer's answer (I don't have the karma to leave comments), you can then add this to Throw404 to send the proper header:

class Throw404(webapp.RequestHandler):
  def get(self):
    self.error(404)
    # your 404 handler goes here
Jackson Miller
+6  A: 

The easiest way to do this is to override the error() method on your base handler (presuming you have one) to generate the 404 page, and call that 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)
Nick Johnson
Wonderful. Thanks for sharing!
PEZ