Python webapp2.HTTPException() Examples

The following are 9 code examples of webapp2.HTTPException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module webapp2 , or try the search function .
Example #1
Source File: start.py    From core with MIT License 6 votes vote down vote up
def dispatcher(router, request, response):
    try:
        if uwsgi is not None:
            uwsgi.set_logvar('request_id', request.id)
    except: # pylint: disable=bare-except
        request.logger.error("Error setting request_id log var", exc_info=True)

    collect_endpoint(request)

    try:
        rv = router.default_dispatcher(request, response)
        if rv is not None:
            response.write(json.dumps(rv, default=encoder.custom_json_serializer))
            response.headers['Content-Type'] = 'application/json; charset=utf-8'
    except webapp2.HTTPException as e:
        util.send_json_http_exception(response, str(e), e.code, request.id)
    except Exception as e: # pylint: disable=broad-except
        request.logger.error("Error dispatching request", exc_info=True)
        if config.get_item('core', 'debug'):
            message = traceback.format_exc()
        else:
            message = 'Internal Server Error'
        util.send_json_http_exception(response, message, 500, request.id) 
Example #2
Source File: __init__.py    From graphene-gae with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_exception(self, exception, debug):
        logging.exception(exception)

        status_code = 500
        if isinstance(exception, webapp2.HTTPException):
            status_code = exception.code

        self.failed_response(status_code, {
            'errors': [self.__format_error(exception)]
        }) 
Example #3
Source File: config.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _instrumented_dispatcher(dispatcher, request, response, time_fn=time.time):
  start_time = time_fn()
  response_status = 0
  flush_thread = None
  time_now = time_fn()
  if need_to_flush_metrics(time_now):
    flush_thread = threading.Thread(target=_flush_metrics, args=(time_now,))
    flush_thread.start()
  try:
    ret = dispatcher(request, response)
  except webapp2.HTTPException as ex:
    response_status = ex.code
    raise
  except Exception:
    response_status = 500
    raise
  else:
    if isinstance(ret, webapp2.Response):
      response = ret
    response_status = response.status_int
  finally:
    if flush_thread:
      flush_thread.join()
    elapsed_ms = int((time_fn() - start_time) * 1000)

    # Use the route template regex, not the request path, to prevent an
    # explosion in possible field values.
    name = request.route.template if request.route is not None else ''

    http_metrics.update_http_server_metrics(
        name, response_status, elapsed_ms,
        request_size=request.content_length,
        response_size=response.content_length,
        user_agent=request.user_agent)

  return ret 
Example #4
Source File: config.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _instrumented_dispatcher(dispatcher, request, response, time_fn=time.time):
  start_time = time_fn()
  response_status = 0
  flush_thread = None
  time_now = time_fn()
  if need_to_flush_metrics(time_now):
    flush_thread = threading.Thread(target=_flush_metrics, args=(time_now,))
    flush_thread.start()
  try:
    ret = dispatcher(request, response)
  except webapp2.HTTPException as ex:
    response_status = ex.code
    raise
  except Exception:
    response_status = 500
    raise
  else:
    if isinstance(ret, webapp2.Response):
      response = ret
    response_status = response.status_int
  finally:
    if flush_thread:
      flush_thread.join()
    elapsed_ms = int((time_fn() - start_time) * 1000)

    # Use the route template regex, not the request path, to prevent an
    # explosion in possible field values.
    name = request.route.template if request.route is not None else ''

    http_metrics.update_http_server_metrics(
        name, response_status, elapsed_ms,
        request_size=request.content_length,
        response_size=response.content_length,
        user_agent=request.user_agent)

  return ret 
Example #5
Source File: config.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _instrumented_dispatcher(dispatcher, request, response, time_fn=time.time):
  start_time = time_fn()
  response_status = 0
  flush_thread = None
  time_now = time_fn()
  if need_to_flush_metrics(time_now):
    flush_thread = threading.Thread(target=_flush_metrics, args=(time_now,))
    flush_thread.start()
  try:
    ret = dispatcher(request, response)
  except webapp2.HTTPException as ex:
    response_status = ex.code
    raise
  except Exception:
    response_status = 500
    raise
  else:
    if isinstance(ret, webapp2.Response):
      response = ret
    response_status = response.status_int
  finally:
    if flush_thread:
      flush_thread.join()
    elapsed_ms = int((time_fn() - start_time) * 1000)

    # Use the route template regex, not the request path, to prevent an
    # explosion in possible field values.
    name = request.route.template if request.route is not None else ''

    http_metrics.update_http_server_metrics(
        name, response_status, elapsed_ms,
        request_size=request.content_length,
        response_size=response.content_length,
        user_agent=request.user_agent)

  return ret 
Example #6
Source File: config.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _instrumented_dispatcher(dispatcher, request, response, time_fn=time.time):
  start_time = time_fn()
  response_status = 0
  flush_thread = None
  time_now = time_fn()
  if need_to_flush_metrics(time_now):
    flush_thread = threading.Thread(target=_flush_metrics, args=(time_now,))
    flush_thread.start()
  try:
    ret = dispatcher(request, response)
  except webapp2.HTTPException as ex:
    response_status = ex.code
    raise
  except Exception:
    response_status = 500
    raise
  else:
    if isinstance(ret, webapp2.Response):
      response = ret
    response_status = response.status_int
  finally:
    if flush_thread:
      flush_thread.join()
    elapsed_ms = int((time_fn() - start_time) * 1000)

    # Use the route template regex, not the request path, to prevent an
    # explosion in possible field values.
    name = request.route.template if request.route is not None else ''

    http_metrics.update_http_server_metrics(
        name, response_status, elapsed_ms,
        request_size=request.content_length,
        response_size=response.content_length,
        user_agent=request.user_agent)

  return ret 
Example #7
Source File: helpers.py    From danforth-east with MIT License 5 votes vote down vote up
def handle_exception(self, exception, debug):
        # Log the error.
        logging.critical('BaseHandler exception', exc_info=exception)

        # Set a custom message.
        if hasattr(exception, 'detail') and getattr(exception, 'detail'):
            self.response.write(getattr(exception, 'detail'))

        # If the exception is a HTTPException, use its error code.
        # Otherwise use a generic 500 error code.
        if isinstance(exception, webapp2.HTTPException):
            self.response.set_status(exception.code)
        else:
            self.response.set_status(500) 
Example #8
Source File: handler_utils.py    From upvote with Apache License 2.0 5 votes vote down vote up
def handle_exception(self, exception, unused_debug_mode):
    """Handle any uncaught exceptions.

    Args:
      exception: The exception that was thrown.
      unused_debug_mode: True if the application is running in debug mode.
    """
    # Default to a 500.
    http_status = httplib.INTERNAL_SERVER_ERROR

    # Calls to abort() raise a child class of HTTPException, so extract the
    # HTTP status and explanation if possible.
    if isinstance(exception, webapp2.HTTPException):
      http_status = getattr(exception, 'code', httplib.INTERNAL_SERVER_ERROR)

      # Write out the exception's explanation to the response body
      escaped_explanation = _HtmlEscape(str(exception))
      self.response.write(escaped_explanation)

    # If the RequestHandler has a corresponding request counter, increment it.
    if self.RequestCounter is not None:
      self.RequestCounter.Increment(http_status)

    # If the exception occurs within a unit test, make sure the stacktrace is
    # easily discerned from the console.
    if not env_utils.RunningInProd():
      exc_type, exc_value, exc_traceback = sys.exc_info()
      traceback.print_exception(exc_type, exc_value, exc_traceback)

    # Set the response code and log the exception regardless.
    self.response.set_status(http_status)
    logging.exception(exception) 
Example #9
Source File: base.py    From core with MIT License 4 votes vote down vote up
def handle_exception(self, exception, debug, return_json=False): # pylint: disable=arguments-differ
        """
        Send JSON response for exception

        For HTTP and other known exceptions, use its error code
        For all others use a generic 500 error code and log the stack trace
        """

        request_id = self.request.id
        custom_errors = None
        message = str(exception)
        if isinstance(exception, webapp2.HTTPException):
            code = exception.code
        elif isinstance(exception, errors.InputValidationException):
            code = 400
        elif isinstance(exception, errors.APIAuthProviderException):
            code = 401
        elif isinstance(exception, errors.APIRefreshTokenException):
            code = 401
            custom_errors = exception.errors
        elif isinstance(exception, errors.APIUnknownUserException):
            code = 402
        elif isinstance(exception, errors.APIConsistencyException):
            code = 400
        elif isinstance(exception, errors.APIPermissionException):
            custom_errors = exception.errors
            code = 403
        elif isinstance(exception, errors.APINotFoundException):
            code = 404
        elif isinstance(exception, errors.APIConflictException):
            code = 409
        elif isinstance(exception, errors.APIValidationException):
            code = 422
            custom_errors = exception.errors
        elif isinstance(exception, errors.FileStoreException):
            code = 400
        elif isinstance(exception, errors.FileFormException):
            code = 400
        elif isinstance(exception, errors.FileFormException):
            code = 400
        elif isinstance(exception, ElasticsearchException):
            code = 503
            message = "Search is currently down. Try again later."
            self.request.logger.error(traceback.format_exc())
        elif isinstance(exception, KeyError):
            code = 500
            message = "Key {} was not found".format(str(exception))
        else:
            code = 500

        if code == 500:
            tb = traceback.format_exc()
            self.request.logger.error(tb)

        if return_json:
            return util.create_json_http_exception_response(message, code, request_id, custom=custom_errors)

        util.send_json_http_exception(self.response, message, code, request_id, custom=custom_errors)