2012-07-09 13 views
8

Na podstawie niektórych googlowań zainstalowałem następujący program obsługi błędów. Jednak wyjątki Pythona, które wydają się zwracać http 500, nie są uwięzione przez te rzeczy, chociaż są 404. Z instrukcjami print, które zostawiłem w poniższym kodzie, widzę, że nie trafił on żadnej z tych procedur. Co powinienem robić?Wyczerpujące obsługa wyjątków aplikacji w aplikacji Tornado

class ErrorHandler(tornado.web.RequestHandler): 
"""Generates an error response with status_code for all requests.""" 
def __init__ (self, application, request, status_code): 
    print 'In ErrorHandler init' 
    tornado.web.RequestHandler.__init__(self, application, request) 
    self.set_status(status_code) 

def get_error_html (self, status_code, **kwargs): 
    print 'In get_error_html. status_code: ', status_code 
    if status_code in [403, 404, 500, 503]: 
     filename = '%d.html' % status_code 
     print 'rendering filename: ', filename 
     return self.render_string(filename, title=config.get_title()) 

    return "<html><title>%(code)d: %(message)s</title>" \ 
      "<body class='bodyErrorPage'>%(code)d: %(message)s</body>"\ 
      "</html>" % { 
      "code": status_code, 
      "message": httplib.responses[status_code], 
      } 

def prepare (self): 
    print 'In prepare...' 
    raise tornado.web.HTTPError(self._status_code) 

Odpowiedz

9

Przede wszystkim, wyjątek, które budzą w prepare ma kod 200, więc to nie jest złapany w funkcji get_error_html.

Po drugie, get_error_html jest przestarzałe: zamiast niego należy użyć write_error (write_error).

Wreszcie nie trzeba zadzwonić na ErrorHandler__init__: zainicjować obsługi używać initialize (initialize), ale w tym przypadku nie jest to potrzebne.

Oto przykład roboczych:

import tornado 
import tornado.web 


class ErrorHandler(tornado.web.RequestHandler): 
    """Generates an error response with status_code for all requests.""" 

    def write_error(self, status_code, **kwargs): 
     print 'In get_error_html. status_code: ', status_code 
     if status_code in [403, 404, 500, 503]: 
      self.write('Error %s' % status_code) 
     else: 
      self.write('BOOM!') 

    def prepare(self): 
     print 'In prepare...' 
     raise Exception('Error!') 


application = tornado.web.Application([ 
     (r"/", ErrorHandler), 
     ]) 

if __name__ == "__main__": 
    application.listen(8899) 
    tornado.ioloop.IOLoop.instance().start() 
+0

Iboola, dziękuję za odpowiedź. Deklarując metodę write_error() dla hanlderów, jestem w stanie uwięzić 500-y; jednak to podejście nie działa tak naprawdę w przypadku obsługi 404 w całej witrynie! Musiałem więc połączyć globalną procedurę obsługi błędów, którą przypisałem do tornado.web.ErrorHandler, oprócz klasy bazowej z metodą write_error(), zgodnie z sugestią użytkownika. Teraz jestem w stanie złapać wyjątki aplikacji, oprócz globalnych 404. – Karra

7
  1. Rączki. Pozwala zdefiniować kilka domyślnych teleskopowe my będziemy używać
import tornado.web 


class BaseHandler(tornado.web.RequestHandler): 
    """ 
    Base handler gonna to be used instead of RequestHandler 
    """ 
    def write_error(self, status_code, **kwargs): 
     if status_code in [403, 404, 500, 503]: 
      self.write('Error %s' % status_code) 
     else: 
      self.write('BOOM!') 


class ErrorHandler(tornado.web.ErrorHandler, BaseHandler): 
    """ 
    Default handler gonna to be used in case of 404 error 
    """ 
    pass 


class MainHandler(BaseHandler): 
    """ 
    Main handler 
    """ 
    def get(self): 
     self.write('Hello world!') 
  1. Ustawienia. Musimy zdefiniować default_handler_class i default_handler_args także
settings = { 
    'default_handler_class': ErrorHandler, 
    'default_handler_args': dict(status_code=404) 
} 
  1. aplikację.
application = tornado.web.Application([ 
    (r"/", MainHandler) 
], **settings) 

jako wynik. wszystkie błędy z wyjątkiem 404 będą obsługiwane przez BaseHandler. 404 - ErrorHandler. to wszystko :)

-1
import tornado.web 


class BaseHandler(tornado.web.RequestHandler): 
    def write_error(self, status_code, **kwargs): 
     print status_code 
     super(BaseHandler, self).write_error(status_code, **kwargs) 
+0

Proszę dodać kontekst, wyjaśnienie lub dowolny odpowiedni komentarz zamiast tylko kodu bezkontekstowego. – Sebastialonso