4

我尝试使用有关如何处理异常的建议功能:

http://webapp-improved.appspot.com/guide/exceptions.html

在 main.py 中:

def handle_404(request, response, exception):
        logging.exception(exception)
        response.write('404 Error')
        response.set_status(404)

def handle_500(request, response, exception):
    logging.exception(exception)
    response.write('A server error occurred!')
    response.set_status(500)

class AdminPage(webapp2.RequestHandler):
    def get(self):
    ...
    admin_id = admin.user_id()
    queues = httpRequests.get_queues(admin_id)

app = webapp2.WSGIApplication(...)

app.error_handlers[404] = handle_404
app.error_handlers[500] = handle_500

httpRequests.py 中的函数:

def get_queues(admin_id):

    url = "http://localhost:8080/api/" + admin_id + "/queues"
    result = urlfetch.fetch(url)

    if (result.status_code == 200):
        received_data = json.loads(result.content)
        return received_data

在 API 中调用的函数:

class Queues(webapp2.RequestHandler): 
    def get(self, admin_id): 
        queues = queues(admin_id)
        if queues == []:
            self.abort(404)
        else:
            self.response.write(json.dumps(queues))

我被困在 httpRequests.py 中的 get_queues 中。如何使用 urlfetch 处理 HTTP 异常?

4

1 回答 1

4

处理错误的另一种方法是创建一个BaseHandlerwithhandle_exception并让所有其他处理程序扩展它。一个完整的示例将如下所示:

import webapp2
from google.appengine.api import urlfetch

class BaseHandler(webapp2.RequestHandler):
  def handle_exception(self, exception, debug_mode):
    if isinstance(exception, urlfetch.DownloadError):
      self.response.out.write('Oups...!')
    else:
      # Display a generic 500 error page.
      pass

class MainHandler(BaseHandler):
  def get(self):
    url = "http://www.google.commm/"
    result = urlfetch.fetch(url)
    self.response.write('Hello world!')


app = webapp2.WSGIApplication([
    ('/', MainHandler)
  ], debug=True)

一个更好的解决方案是在调试模式下运行时抛出异常,并在生产中运行时以更友好的方式处理它们。取自另一个示例,您可以为您做类似的事情BaseHandler并根据需要扩展它:

class BaseHandler(webapp2.RequestHandler):
  def handle_exception(self, exception, debug_mode):
    if not debug_mode:
      super(BaseHandler, self).handle_exception(exception, debug_mode)
    else:
      if isinstance(exception, urlfetch.DownloadError):
        # Display a download-specific error page
        pass
      else:
        # Display a generic 500 error page.
        pass
于 2013-09-05T22:20:48.333 回答