Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to catch this Error (can't source error name) - binascii.Error

I'm using the base64 module for the b64decode() function, however certain strings of text throw this error:

'binascii.Error: Incorrect Padding'.

I understand that this is because the strings are not of length multiple of 4, a requirement of base64 encoded text.

Rather than just adding '='s to the end of the string to make it a multiple of 4, I want to catch the error and simply state that the string is not base64 encoded. It works using a general 'except:', however I want to catch the specific error, but I can't find out the same of the error, as it is not very specific as with other errors, and 'except binascii.Error:' is apparently undefined. Help?

like image 935
Jckxxlaw Avatar asked Apr 22 '17 15:04

Jckxxlaw


2 Answers

The exception type is stored in binascii.Error, there's multiple ways of catching the exception:

# 1. you can import the binascii module
import binascii
try:
    pass
except binascii.Error as err:
    pass


# 2. or you can use the binascii from base64's namespace

try:
    pass
except base64.binascii.Error as err:
    pass


# 3. or you can use __import__ to do a temp import

try:
    pass
except __import__('binascii').Error as err:
    pass
like image 103
Taku Avatar answered Oct 16 '22 08:10

Taku


The reason

except binascii.Error

didn't work is because binascii was imported from within the base64 namespace, so it was undefined in my working namespace. The correct way to catch the error was

except base64.binascii.Error

Amature mistake

like image 6
Jckxxlaw Avatar answered Oct 16 '22 06:10

Jckxxlaw