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

エラーを処理するもう 1 つの方法は、BaseHandlerwithを作成しhandle_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 に答える