From 0729e38e2f5bbc5ab23153adfed3d35ee59dc3d5 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Fri, 27 Sep 2024 11:40:08 -0500 Subject: Extract common functionality into reusable function. --- uploader/monadic_requests.py | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) (limited to 'uploader/monadic_requests.py') diff --git a/uploader/monadic_requests.py b/uploader/monadic_requests.py index aa34951..c492df5 100644 --- a/uploader/monadic_requests.py +++ b/uploader/monadic_requests.py @@ -5,13 +5,12 @@ from typing import Union, Optional, Callable import requests from requests.models import Response from pymonad.either import Left, Right, Either -from flask import ( - flash, - request, - redirect, - render_template, - current_app as app, - escape as flask_escape) +from flask import (flash, + request, + redirect, + render_template, + current_app as app, + escape as flask_escape) # HTML Status codes indicating a successful request. SUCCESS_CODES = (200, 201, 202, 203, 204, 205, 206, 207, 208, 226) @@ -84,3 +83,22 @@ def post(url, data=None, json=None, **kwargs) -> Either: return Left(resp) except requests.exceptions.RequestException as exc: return Left(exc) + + +def make_either_error_handler(msg): + """Make generic error handler for pymonads Either objects.""" + def __fail__(error): + if issubclass(type(error), Exception): + app.logger.debug("\n\n%s (Exception)\n\n", msg, exc_info=True) + raise error + if issubclass(type(error), Response): + try: + _data = error.json() + except Exception as _exc: + raise Exception(error.content) from _exc + raise Exception(_data) + + app.logger.debug("\n\n%s\n\n", msg) + raise Exception(error) + + return __fail__ -- cgit v1.2.3