From 1a5b2d166fc95e5f3f07fdfec075acdf4d0eda92 Mon Sep 17 00:00:00 2001 From: Ram Rachum Date: Fri, 19 Jun 2020 23:39:00 +0300 Subject: Fix exception causes all over the codebase The mistake is this: In some parts of the code, an exception is being caught and replaced with a more user-friendly error. In these cases the syntax `raise new_error from old_error` needs to be used. Python's exception chaining means it shows not only the traceback of the current exception, but that of the original exception (and possibly more.) This is regardless of `raise from`. The usage of `raise from` tells Python to put a more accurate message between the tracebacks. Instead of this: During handling of the above exception, another exception occurred: You'll get this: The above exception was the direct cause of the following exception: The first is inaccurate, because it signifies a bug in the exception-handling code itself, which is a separate situation than wrapping an exception. --- rsa/key.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'rsa/key.py') diff --git a/rsa/key.py b/rsa/key.py index e61bac1..620ab5a 100644 --- a/rsa/key.py +++ b/rsa/key.py @@ -131,10 +131,10 @@ class AbstractKey: try: return methods[file_format] - except KeyError: + except KeyError as ex: formats = ', '.join(sorted(methods.keys())) raise ValueError('Unsupported format: %r, try one of %s' % (file_format, - formats)) + formats)) from ex def save_pkcs1(self, format: str = 'PEM') -> bytes: """Saves the key in PKCS#1 DER or PEM format. @@ -703,7 +703,7 @@ def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> typing.Tupl raise rsa.common.NotRelativePrimeError( exponent, phi_n, ex.d, msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" % - (exponent, phi_n, ex.d)) + (exponent, phi_n, ex.d)) from ex if (exponent * d) % phi_n != 1: raise ValueError("e (%d) and d (%d) are not mult. inv. modulo " -- cgit v1.2.1