[wxPython-users] Better exception handling

Werner F. Bruhin werner.bruhin at free.fr
Thu Jun 28 10:05:21 PDT 2007


Hi Jorgen,

Jorgen Bodde wrote:
> Hi All,
>
> I love wxPython! One thing that worries me for my end-users is the
> inability to see potential errors. When my GUI app is ran from a
> console window, the exception is thrown in there. But when somethign
> happens and the console window is not there, I would like to see an
> error window similar to the stack walker. The way it is now, errors
> and exceptions are eaten if I rename my app's extension to myapp.pyw
> ..
>
> I would not like that as it leads to undesired behaviour and people
> not seeing an error and think a particular button does not do anything
> can cause more harm then showing an error dialog. Also if there is no
> feedback, not many people will file a report.
>
> Is there a way to get errors back from python's exceptions when there
> is no console window??
You already got suggestions from others but here a few more on how you 
could handle exceptions.

I redirect both stdout and stderr to files, then have an option to log 
all the SQL command (as my app uses a db) and then define an exception 
handler which puts a time stamp into the log file and logs the exception 
and puts up a dialog showing the error log files, catching the version 
information (OS and my app version) and it has an option for the user to 
send the errors via SMTP or MAPI to a support e-mail address.


The following are a few code snippets which might be useful.

        self.RedirectLogFiles()
        sys.excepthook = self.MyExceptionHandler

    def RedirectLogFiles(self):
        sp = wx.StandardPaths.Get()
        userdir, userdoc = os.path.split(sp.GetDocumentsDir())
        logFolder = os.path.join(userdir, 'YourAppName')
        if not os.path.exists(logFolder):
            os.mkdir(logFolder)
       
        sqllogFile = os.path.join(logFolder, 'sqllog.txt')
        stdoutFile = os.path.join(logFolder, 'stdoutlog.txt')
        stderrFile = os.path.join(logFolder, 'stderrlog.txt')

        self.sqllog = file(sqllogFile, 'a+')
        self.stdoutlog = file(stdoutFile, 'a+')
        self.stderrlog = file(stderrFile, 'a+')

        sys.stdout = self.stdoutlog
        sys.stderr = self.stderrlog

    def MyExceptionHandler(self, type, value, trace_back):
        """Catch exceptions, log them to file and show error dialog
        """       
        timestamp = myTime.asctime(myTime.localtime(myTime.time()))
        self.stdoutlog.write('**** %s ****\n' % timestamp)
        traceback.print_exception(type, value, trace_back, 
file=self.stdoutlog)
        self.stdoutlog.write('\n')
        # to ensure that errorDialog is shown immediatly
        self.stdoutlog.flush()
       
        self.ReportException(msg=2)     

Best regards
Werner




More information about the wxpython-users mailing list