[CHORE] E722 bare exception fix (#1871)

* [CHORE] E722 bare exception fix
remove all bare exceptions from codebase and change it in `.flake8`
This commit is contained in:
dni ⚡ 2023-08-16 12:17:54 +02:00 committed by GitHub
parent 3aef1605be
commit 355806608b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 48 additions and 50 deletions

View file

@ -10,7 +10,5 @@ ignore =
W503,
# F821: undefined name - should be addressed in future PR
F821,
# E722 do not use bare 'except' - should be addressed in future PR
E722,
# flake8-requirements import checks
I

View file

@ -133,7 +133,7 @@ async def check_funding_source() -> None:
f"The backend for {WALLET.__class__.__name__} isn't working properly: '{error_message}'",
RuntimeWarning,
)
except:
except Exception:
pass
if settings.lnbits_admin_ui and retry_counter == timeout:

View file

@ -520,7 +520,7 @@ async def create_payment(
try:
invoice = bolt11.decode(payment_request)
expiration_date = datetime.datetime.fromtimestamp(invoice.date + invoice.expiry)
except:
except Exception:
# assume maximum bolt11 expiry of 31 days to be on the safe side
expiration_date = datetime.datetime.now() + datetime.timedelta(days=31)

View file

@ -71,7 +71,7 @@ def to_valid_user_id(user_id: str) -> UUID:
raise ValueError("User ID must have at least 128 bits")
try:
int(user_id, 16)
except:
except Exception:
raise ValueError("Invalid hex string for User ID.")
return UUID(hex=user_id[:32], version=4)

View file

@ -251,7 +251,7 @@ async def m007_set_invoice_expiries(db):
checking_id,
),
)
except:
except Exception:
continue
except OperationalError:
# this is necessary now because it may be the case that this migration will

View file

@ -41,7 +41,7 @@ class Wallet(BaseModel):
url = url_for("/withdraw", external=True, usr=self.user, wal=self.id)
try:
return lnurl_encode(url)
except:
except Exception:
return ""
def lnurlauth_key(self, domain: str) -> SigningKey:

View file

@ -299,7 +299,7 @@ async def redeem_lnurl_withdraw(
extra=extra,
conn=conn,
)
except:
except Exception:
logger.warning(
f"failed to create invoice on redeem_lnurl_withdraw from {lnurl}. params: {res}"
)
@ -495,7 +495,7 @@ def update_cached_settings(sets_dict: dict):
if key not in readonly_variables:
try:
setattr(settings, key, value)
except:
except Exception:
logger.warning(f"Failed overriding setting: {key}, value: {value}")
if "super_user" in sets_dict:
setattr(settings, "super_user", sets_dict["super_user"])

View file

@ -34,7 +34,7 @@ async def api_auditor():
"node_balance_msats": int(node_balance),
"lnbits_balance_msats": int(total_balance),
}
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail="Could not audit balance.",
@ -94,7 +94,7 @@ async def api_topup_balance(
) -> dict[str, str]:
try:
await get_wallet(id)
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="wallet does not exist."
)

View file

@ -513,7 +513,7 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type
try:
url = lnurl.decode(code)
domain = urlparse(url).netloc
except:
except Exception:
# parse internet identifier (user@domain.com)
name_domain = code.split("@")
if len(name_domain) == 2 and len(name_domain[1].split(".")) >= 2:
@ -648,7 +648,7 @@ async def api_payments_decode(data: DecodePayment, response: Response):
"route_hints": invoice.route_hints,
"min_final_cltv_expiry": invoice.min_final_cltv_expiry,
}
except:
except Exception:
response.status_code = HTTPStatus.BAD_REQUEST
return {"message": "Failed to decode"}
@ -743,7 +743,7 @@ async def websocket_update_post(item_id: str, data: str):
try:
await websocketUpdater(item_id, data)
return {"sent": True, "data": data}
except:
except Exception:
return {"sent": False, "data": data}
@ -752,7 +752,7 @@ async def websocket_update_get(item_id: str, data: str):
try:
await websocketUpdater(item_id, data)
return {"sent": True, "data": data}
except:
except Exception:
return {"sent": False, "data": data}
@ -930,7 +930,7 @@ async def api_create_tinyurl(
if tinyurl.wallet == wallet.wallet.inkey:
return tinyurl
return await create_tinyurl(url, endless, wallet.wallet.inkey)
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Unable to create tinyurl"
)
@ -948,7 +948,7 @@ async def api_get_tinyurl(
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided."
)
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Unable to fetch tinyurl"
)
@ -967,7 +967,7 @@ async def api_delete_tinyurl(
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="Wrong key provided."
)
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Unable to delete"
)
@ -982,7 +982,7 @@ async def api_tinyurl(tinyurl_id: str):
return response
else:
return
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="unable to find tinyurl"
)

View file

@ -275,7 +275,7 @@ async def lnurl_full_withdraw_callback(request: Request):
async def pay():
try:
await pay_invoice(wallet_id=wallet.id, payment_request=pr)
except:
except Exception:
pass
asyncio.create_task(pay())

View file

@ -28,7 +28,7 @@ async def api_public_payment_longpolling(payment_hash):
expiration = datetime.datetime.fromtimestamp(invoice.date + invoice.expiry)
if expiration < datetime.datetime.now():
return {"status": "expired"}
except:
except Exception:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Invalid bolt11 invoice."
)

View file

@ -173,7 +173,7 @@ async def get_key_type(
pass
else:
raise
except:
except Exception:
raise
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Wallet does not exist."

View file

@ -86,7 +86,7 @@ def get_current_extension_name() -> str:
with open(config_path) as json_file:
config = json.load(json_file)
ext_name = config["name"]
except:
except Exception:
ext_name = extension_director_name
return ext_name

View file

@ -388,7 +388,7 @@ try:
.strip()
.decode("ascii")
)
except:
except Exception:
settings.lnbits_commit = "docker"
settings.version = importlib.metadata.version("lnbits")

View file

@ -36,7 +36,7 @@ class ClicheWallet(Wallet):
)
try:
data = json.loads(r)
except:
except Exception:
return StatusResponse(
f"Failed to connect to {self.endpoint}, got: '{r[:200]}...'", 0
)
@ -168,7 +168,7 @@ class ClicheWallet(Wallet):
try:
if data["result"]["status"]:
yield data["result"]["payment_hash"]
except:
except Exception:
continue
except Exception as exc:
logger.error(

View file

@ -135,7 +135,7 @@ class CoreLightningWallet(Wallet):
except RpcError as exc:
try:
error_message = exc.error["attempts"][-1]["fail_reason"]
except:
except Exception:
error_message = f"CLN method '{exc.method}' failed with '{exc.error.get('message') or exc.error}'."
return PaymentResponse(False, None, None, None, error_message)
except Exception as exc:
@ -149,7 +149,7 @@ class CoreLightningWallet(Wallet):
async def get_invoice_status(self, checking_id: str) -> PaymentStatus:
try:
r = self.ln.listinvoices(payment_hash=checking_id)
except:
except Exception:
return PaymentStatus(None)
if not r["invoices"]:
return PaymentStatus(None)
@ -170,7 +170,7 @@ class CoreLightningWallet(Wallet):
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
try:
r = self.ln.listpays(payment_hash=checking_id)
except:
except Exception:
return PaymentStatus(None)
if "pays" not in r or not r["pays"]:
return PaymentStatus(None)

View file

@ -53,7 +53,7 @@ class EclairWallet(Wallet):
r = await self.client.post("/globalbalance", timeout=5)
try:
data = r.json()
except:
except Exception:
return StatusResponse(
f"Failed to connect to {self.url}, got: '{r.text[:200]}...'", 0
)
@ -93,7 +93,7 @@ class EclairWallet(Wallet):
try:
data = r.json()
error_message = data["error"]
except:
except Exception:
error_message = r.text
return InvoiceResponse(False, None, None, error_message)
@ -112,7 +112,7 @@ class EclairWallet(Wallet):
try:
data = r.json()
error_message = data["error"]
except:
except Exception:
error_message = r.text
return PaymentResponse(False, None, None, None, error_message)
@ -136,7 +136,7 @@ class EclairWallet(Wallet):
try:
data = r.json()
error_message = data["error"]
except:
except Exception:
error_message = r.text
return PaymentResponse(None, checking_id, None, preimage, error_message)
@ -175,7 +175,7 @@ class EclairWallet(Wallet):
"pending": None,
}
return PaymentStatus(statuses.get(data["status"]["type"]))
except:
except Exception:
return PaymentStatus(None)
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
@ -206,7 +206,7 @@ class EclairWallet(Wallet):
return PaymentStatus(
statuses.get(data["status"]["type"]), fee_msat, preimage
)
except:
except Exception:
return PaymentStatus(None)
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:

View file

@ -47,7 +47,7 @@ class LNbitsWallet(Wallet):
try:
data = r.json()
except:
except Exception:
return StatusResponse(
f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0
)
@ -117,7 +117,7 @@ class LNbitsWallet(Wallet):
if r.is_error:
return PaymentStatus(None)
return PaymentStatus(r.json()["paid"])
except:
except Exception:
return PaymentStatus(None)
async def get_payment_status(self, checking_id: str) -> PaymentStatus:

View file

@ -83,7 +83,7 @@ def hex_to_b64(hex_str: str) -> str:
def hex_to_bytes(hex_str: str) -> bytes:
try:
return bytes.fromhex(hex_str)
except:
except Exception:
return b""
@ -289,7 +289,7 @@ class LndWallet(Wallet):
bytes_to_hex(payment.htlcs[-1].preimage),
)
return PaymentStatus(statuses[payment.status])
except: # most likely the payment wasn't found
except Exception: # most likely the payment wasn't found
return PaymentStatus(None)
return PaymentStatus(None)

View file

@ -201,7 +201,7 @@ class LndRestWallet(Wallet):
)
else:
return PaymentStatus(None)
except:
except Exception:
continue
return PaymentStatus(None)
@ -216,7 +216,7 @@ class LndRestWallet(Wallet):
inv = json.loads(line)["result"]
if not inv["settled"]:
continue
except:
except Exception:
continue
payment_hash = base64.b64decode(inv["r_hash"]).hex()

View file

@ -102,7 +102,7 @@ class LNPayWallet(Wallet):
try:
data = r.json()
except:
except Exception:
return PaymentResponse(
False, None, 0, None, f"Got invalid JSON: {r.text[:200]}"
)

View file

@ -42,7 +42,7 @@ class LnTipsWallet(Wallet):
r = await self.client.get("/api/v1/balance", timeout=40)
try:
data = r.json()
except:
except Exception:
return StatusResponse(
f"Failed to connect to {self.endpoint}, got: '{r.text[:200]}...'", 0
)
@ -76,7 +76,7 @@ class LnTipsWallet(Wallet):
try:
data = r.json()
error_message = data["message"]
except:
except Exception:
error_message = r.text
return InvoiceResponse(False, None, None, error_message)
@ -99,7 +99,7 @@ class LnTipsWallet(Wallet):
try:
data = r.json()
error_message = data["error"]
except:
except Exception:
error_message = r.text
return PaymentResponse(False, None, 0, None, error_message)
@ -120,7 +120,7 @@ class LnTipsWallet(Wallet):
data = r.json()
return PaymentStatus(data["paid"])
except:
except Exception:
return PaymentStatus(None)
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
@ -135,7 +135,7 @@ class LnTipsWallet(Wallet):
paid_to_status = {False: None, True: True}
return PaymentStatus(paid_to_status[data.get("paid")])
except:
except Exception:
return PaymentStatus(None)
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
@ -154,7 +154,7 @@ class LnTipsWallet(Wallet):
inv = json.loads(data)
if not inv.get("payment_hash"):
continue
except:
except Exception:
continue
yield inv["payment_hash"]
except Exception:

View file

@ -27,7 +27,7 @@ def load_macaroon(macaroon: str) -> str:
# convert the bas64 macaroon to hex
try:
macaroon = base64.b64decode(macaroon).hex()
except:
except Exception:
pass
return macaroon

View file

@ -73,7 +73,7 @@ class SparkWallet(Wallet):
try:
data = r.json()
except:
except Exception:
raise UnknownError(r.text)
if r.is_error: