How to remove __main__. in Python error handling

163 views Asked by At

I am trying to generate custom exception in Python. Below is my code.

class numerror(Exception):
    
    def __init__(self):
        message = "invalid number"
        dict = {'nmerror': message}
        err = json.dumps(dict)
        super().__init__(err)
        

        .
        .
        except numerror as e:
        return e
        

Below is the output.

{'error': __main__.numerror('{"nmerror": "invalid number"}')}

I want to remove __main__.numerror and expected output is below.

'{"nmerror": "invalid number"}'

Is there anyway to achieve this. Thankyou.

1

There are 1 answers

0
jsbueno On

The __main__ in there is a qualified name + class name, which is displayed as part of the repr of an exception.

It is not an "output" per se: if you want to check that in code, you should retrieve the exception .args attribute. If the excetpion is being printed and you want to filter that in the output, however, you can simply create a new __repr__ method for your custom exception:

class numerror(Exception):
    
    def __init__(self):
        message = "invalid number"
        dict = {'nmerror': message}
        err = json.dumps(dict)
        super().__init__(err)

    def __repr__(self):
        return str(self.args[0])