Python中的异常处理(webapp2,Google App Engine)

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异常?


这就是代码:if result.status_code == 200: - topless
它没有处理异常。我想要类似于以下代码的东西: try: urlfetch.fetch(url) except urlfetch.Error, e: logging.error('Caught exception fetching url: %s', e) - user2653179
1个回答

4
另一种处理错误的方法是创建一个带有handle_exception方法的BaseHandler,并让所有其他处理程序扩展此处理程序。一个完整可工作的示例如下所示:
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

感谢回答,但我仍然不确定如何在“result = urlfetch.fetch(url)”中检查是否有404异常等。 - user2653179

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接