'How to print human readable exception/error output in python?
I have a script that checks if multiple components of a script fails. Instead of throwing an exception every time there is a failure, I have a list that starts off empty but then failures that occur are appended to the list. Then, at the end of the script it throws an error if the length of the list is not equal to 0. If there are a lot of errors, it ends up turning into a long string that is hard to read. I am trying to find a way to make it human readable but I can't find anything. I have tried using a newline character, but it just outputs with '\n'
instead of creating a new line.
Here is an example.
errors = ['1. First check: e3 failed',
'2. Second check: d1 did not show up, d2 did not show up',
'3. Third check: e2 failed, r4 failed, f5 failed']
if len(errors) != 0 :
raise ValueError(' '.join(errors))
this outputs:
ValueError('1. First check: e3 failed 2. Second check: d1 did not show up, d2 did not show up 3. Third check: e2 failed, r4 failed, f5 failed')
I tried adding a newline character as mentioned above:
err_output = '\n'.join(errors)
if len(errors) != 0 :
raise ValueError(err_output)
this outputs:
ValueError('1. First check: e3 failed\n2. Second check: d1 did not show up, d2 did not show up\n3. Third check: e2 failed, r4 failed, f5 failed')
I'm looking for something like:
ValueError('1. First check: e3 failed
2. Second check: d1 did not show up, d2 did not show up
3. Third check: e2 failed, r4 failed, f5 failed')
Solution 1:[1]
The problem in the first case is that you're joining the array of strings with a space character, to obtain your desired output, you should join said array on a \n
. Your second attempt should be fine, except for that you're not calling raise ValueError(err_output)
, but instead you call raise ValueError(errors)
.
By doing something like this, you should obtain your desired output:
errors=[]
errors.append('Error 1')
errors.append('Error 2')
error_output = '\n'.join(errors)
raise ValueError(error_output)
Output:
Traceback (most recent call last):
File "test.py", line 5, in <module>
raise ValueError(error_output)
ValueError: Error 1
Error 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CcmU |