我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用aiohttp.web.HTTPException()。
def error_pages(overrides): async def middleware(app, handler): async def middleware_handler(request): try: response = await handler(request) override = overrides.get(response.status) if override is None: return response else: return await override(request, response) except web.HTTPException as ex: override = overrides.get(ex.status) if override is None: raise else: return await override(request, ex) return middleware_handler return middleware
def create_handler(transmute_func, context): @wraps(transmute_func.raw_func) async def handler(request): exc, result = None, None try: args, kwargs = await extract_params(request, context, transmute_func) result = await transmute_func.raw_func(*args, **kwargs) except HTTPException as hpe: code = hpe.status_code or 400 exc = APIException(code=code, message=str(hpe)) except Exception as e: exc = e response = transmute_func.process_result( context, result, exc, request.content_type ) return web.Response( body=response["body"], status=response["code"], content_type=response["content-type"], headers=response["headers"] ) handler.transmute_func = transmute_func return handler
def error_pages(overrides): async def middleware(app, handler): async def middleware_handler(request): try: response = await handler(request) override = overrides.get(response.status) if override is None: return response else: return await override(request, response) except web.HTTPException as ex: override = overrides.get(ex.status) if override is None: return await handle_any(request, ex) else: return await override(request, ex) except Exception as ex: return await handle_500(request, error=ex) return middleware_handler return middleware
def error_middleware(app, handler): @asyncio.coroutine def middleware_handler(request): try: response = yield from handler(request) return response except web.HTTPException as ex: resp = web.Response(body=str(ex), status=ex.status) return resp except Exception as ex: resp = web.Response(body=str(ex), status=500) return resp return middleware_handler
def errors_middleware(app, handler): show_error_details = configuration.show_error_details async def errors_middleware_handler(request): # sets arrays in the request object, that can be manipulated to insert or remove cookies for the response. try: response = await handler(request) except HTTPException as e: return e except HTTPClientError as e: return e except Exception as ex: if show_error_details: # return error details to the client return error(message=str(ex)) # hide error details return error() return response return errors_middleware_handler
def error_middleware(app, handler): async def middleware_handler(request): try: response = await handler(request) if response.status == 404: return await http_404_response(request) elif response.status == 403: return web.HTTPFound('/auth/login') return response except web.HTTPException as ex: if ex.status == 404: return await http_404_response(request) elif ex.status == 403: return web.HTTPFound('/auth/login') raise return middleware_handler
def error_middleware(app, handler): async def middleware_handler(request): if_trace = request.query.get('trace') if 'trace' in request.query and request.query.get('trace') == '1' else None try: response = await handler(request) if response.status == 404: return handle_api_exception({"code": response.status, "message": response.message}, ex.__class__.__name__, if_trace) return response except (web.HTTPNotFound, web.HTTPBadRequest) as ex: return handle_api_exception({"code": ex.status_code, "message": ex.reason}, ex.__class__.__name__, if_trace) except web.HTTPException as ex: raise # Below Exception must come last as it is the super class of all exceptions except Exception as ex: return handle_api_exception(ex, ex.__class__.__name__, if_trace) return middleware_handler
def auth_middleware(app, handler): async def middleware_handler(request): try: # check auth header if not request.path == "/api/v1/session": token = request.headers.get("X-Auth-Token") if token not in _tokens.values(): return web.json_response({"error": "Invalid token."}, status=401) # return response response = await handler(request) return response except web.HTTPException as ex: raise return middleware_handler
def error_overrides(overrides): async def middleware(app, handler): async def middleware_handler(request): try: response = await handler(request) return response except web.HTTPException as ex: override = overrides.get(ex.status) if override: return await override(request, ex) return middleware_handler return middleware
def middleware(app, handler): async def middleware_handler(request): setattr(request, 'csrf_token', await get_token(request)) try: response = await awaitable(handler(request)) except web.HTTPException as e: raise e return response return middleware_handler
def error_middleware(app, handler): async def middleware_handler(request): try: response = await handler(request) if response.status != 200: return json_error(response.message) return response except web.HTTPException as ex: return json_error(ex.reason) except ChromewhipException as ex: return json_error(ex.args[0]) except Exception as ex: verbose_tb = traceback.format_exc() return json_error(verbose_tb) return middleware_handler
def error_middleware(app, next_handler): async def handler(request): try: result = await next_handler(request) except Exception as exc: if isinstance(exc, ValidationError): result = ErrorResponse( data={ 'message': 'Validation error', 'errors': exc.errors }, status=HTTP_BAD_REQUEST ) elif not isinstance(exc, HTTPException): # pragma: no cover message = 'An error has occurred' logger.exception(message) result = ErrorResponse( data={'message': message}, status=HTTP_INTERNAL_SERVER_ERROR ) else: if exc.empty_body: # currently we dont use exceptions without body # so don't cover this line for a while raise exc # pragma: no cover result = ErrorResponse( data={'message': exc.reason}, status=exc.status, headers=exc.headers ) return result return handler
def middleware_exception(app, handler): @wraps(handler) @asyncio.coroutine def middleware_handler(request): try: return (yield from handler(request)) except HTTPException as e: if not isinstance(e, HTTPExceptionJson): return HTTPExceptionJson(status_code=e.status, text=e.reason) return e return middleware_handler
def _dispatch(self, action, actionName): self._private.layout = getattr(self.__class__, 'LAYOUT') if not self.request.is_ajax() else Controller.EMPTY_LAYOUT self._private.template = os.path.join(self._private.search_path, self._private.controller, '%s.html' % actionName) self._private.session = await get_session(self.request) self._private.flash = Flash(self._private.session) # TODO: something better beforeActionRes = {} for beforeAction in getattr(self.__class__, '__BEFORE_ACTIONS', []): if actionName not in beforeAction[CtlDecoratorDescriptor.EXCEPT] and \ (actionName in beforeAction[CtlDecoratorDescriptor.ONLY] or len(beforeAction[CtlDecoratorDescriptor.ONLY]) == 0): res = await awaitable(beforeAction[CtlDecoratorDescriptor.VAL](self)) if isinstance(res, web.Response): return res if isinstance(res, dict): beforeActionRes.update(res) try: res = await awaitable(action()) except web.HTTPException as e: self._private.flash.sync() raise e except Exception as e: self._private.flash.sync() raise web.HTTPInternalServerError() if isinstance(res, web.Response): self._private.flash.sync() return res if res is None: res = {} res.update(beforeActionRes) response = await self.request.serializer.serialize(res) try: headers = getattr(self.__class__, '__HEADERS') for name in headers: descriptior = headers[name] if actionName not in descriptior[CtlDecoratorDescriptor.EXCEPT] and \ (actionName in descriptior[CtlDecoratorDescriptor.ONLY] or len(descriptior[CtlDecoratorDescriptor.ONLY]) == 0): response.headers[name] = descriptior[CtlDecoratorDescriptor.VAL] except AttributeError: pass self._private.flash.sync() return response