Use exceptions instead of uncontrollable wxLogMessage

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
neo_in_matrix
Knows some wx things
Knows some wx things
Posts: 45
Joined: Thu Mar 31, 2005 7:38 am

Use exceptions instead of uncontrollable wxLogMessage

Post by neo_in_matrix »

I have created a wxLog-derived class that enable the popular try/catch method of catching erros in wxWidgets. It's quite small, so I directly paste it below.

Code: Select all

struct wxMyLogException
{
public:
    wxMyLogException(time_t ts, const wxChar* msg, wxLogLevel level = (wxLogLevel)-1)
    {
		this->ts = ts;
		this->level = level;
		this->msg = msg;
	}
	
	time_t  	ts;
	wxLogLevel  level;
	wxString    msg;
};

class wxMyLog: public wxLog
{
private:

public:
	virtual void DoLog(wxLogLevel level, const wxChar *msg, time_t timestamp)
	{
        throw wxMyLogException(timestamp, msg, level);
	}

	virtual void DoLogString(const wxChar *msg, time_t timestamp)
	{
		throw wxMyLogException(timestamp, msg);
	}
};
To use this calss, create a member variable m_log of type wxMyLog and in wxYourApp::OnInit, code like this:

Code: Select all

bool MyApp::OnInit()
{
	wxLog::SetActiveTarget(&m_log)
}
Then you can code like this

Code: Select all

try
{
    // Operations that may raise wxLog messages
}
catch(wxMyLogException& e)
{
    wxDateTime ts(e.ts);
    string s;
    s.Printf(_("%s:\r\n    %s"), ts.Format().c_str(), e.msg.c_str());
    wxMessageBox(s);
}
mjs
Experienced Solver
Experienced Solver
Posts: 93
Joined: Wed Feb 09, 2005 3:53 am
Contact:

Post by mjs »

I'd like to see an enhancement that an exception will be thrown only when an error must be logged - and not a warning (or even a verbose message).

BTW: The documentation for wxLog*() functions must be changed to say something like "... may throw an exception - but is not required to."

Regards,
Mark
Post Reply