Rewrite Python error handling to show meaningful messages.

This commit is contained in:
Teo Mrnjavac 2014-07-22 17:48:05 +02:00
parent 0234415976
commit c6c2c67560

View File

@ -212,23 +212,67 @@ Helper::createCleanNamespace()
QString QString
Helper::handleLastError() Helper::handleLastError()
{ {
using namespace boost::python; PyObject *type = nullptr, *val = nullptr, *tb = nullptr;
using namespace boost; PyErr_Fetch( &type, &val, &tb );
PyObject *exc,*val,*tb; QString typeMsg;
object formatted_list, formatted; if ( type != nullptr )
PyErr_Fetch(&exc,&val,&tb); {
handle<> hexc(exc),hval(allow_null(val)),htb(allow_null(tb)); bp::handle<> h_type( type );
object traceback(import("traceback")); bp::str pystr( h_type );
if (!tb) { bp::extract< std::string > extracted( pystr );
object format_exception_only(traceback.attr("format_exception_only")); if ( extracted.check() )
formatted_list = format_exception_only(hexc,hval); typeMsg = QString::fromStdString( extracted() ).toHtmlEscaped();
} else {
object format_exception(traceback.attr("format_exception")); if ( typeMsg.trimmed().isEmpty() )
formatted_list = format_exception(hexc,hval,htb); typeMsg = tr( "Unknown exception type" );
} }
formatted = str("\n").join(formatted_list);
return QString::fromStdString( extract<std::string>(formatted) ); QString valMsg;
if ( val != nullptr )
{
bp::handle<> h_val( val );
bp::str pystr( h_val );
bp::extract< std::string > extracted( pystr );
if ( extracted.check() )
valMsg = QString::fromStdString( extracted() ).toHtmlEscaped();
if ( valMsg.trimmed().isEmpty() )
valMsg = tr( "unparseable Python error" );
}
QString tbMsg;
if ( tb != nullptr )
{
bp::handle<> h_tb( tb );
bp::object tb( bp::import( "traceback" ) );
bp::object format_tb( tb.attr( "format_tb" ) );
bp::object tb_list( format_tb( h_tb ) );
bp::object pystr( bp::str( "\n" ).join( tb_list ) );
bp::extract< std::string > extracted( pystr );
if ( extracted.check() )
tbMsg = QString::fromStdString( extracted() ).toHtmlEscaped();
if ( tbMsg.trimmed().isEmpty() )
tbMsg = tr( "unparseable Python traceback" );
}
if ( typeMsg.isEmpty() && valMsg.isEmpty() && tbMsg.isEmpty() )
return tr( "Unfetchable Python error." );
QStringList msgList;
if ( !typeMsg.isEmpty() )
msgList.append( QString( "<strong>%1</strong>" ).arg( typeMsg ) );
if ( !valMsg.isEmpty() )
msgList.append( valMsg );
if ( !tbMsg.isEmpty() )
msgList.append( QString( "</code>Traceback:<code><br/>%1" ).arg( tbMsg ) );
return QString( "<code>%1</code>" ).arg( msgList.join( "<br/>" ) );
} }