Fix throwing of exceptions from Python to JS

This commit is contained in:
Michael Droettboom 2018-03-07 11:05:08 -05:00
parent d7e4cb8a9c
commit 5bfe045262
1 changed files with 22 additions and 8 deletions

View File

@ -10,6 +10,7 @@ val pythonExcToJs() {
PyObject *type; PyObject *type;
PyObject *value; PyObject *value;
PyObject *traceback; PyObject *traceback;
bool no_traceback = false;
PyErr_Fetch(&type, &value, &traceback); PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback);
@ -20,15 +21,27 @@ val pythonExcToJs() {
if (tbmod == NULL) { if (tbmod == NULL) {
excval = val("Couldn't get traceback module"); excval = val("Couldn't get traceback module");
} else { } else {
PyObject *format_exception = PyObject_GetAttrString(tbmod, "format_exception"); PyObject *format_exception;
if (traceback == NULL || traceback == Py_None) {
no_traceback = true;
format_exception = PyObject_GetAttrString(tbmod, "format_exception_only");
} else {
format_exception = PyObject_GetAttrString(tbmod, "format_exception");
}
if (format_exception == NULL) { if (format_exception == NULL) {
excval = val("Couldn't get format_exception function"); excval = val("Couldn't get format_exception function");
} else { } else {
PyObject *pylines = PyObject_CallFunctionObjArgs PyObject *pylines;
if (no_traceback) {
pylines = PyObject_CallFunctionObjArgs
(format_exception, type, value, NULL);
} else {
pylines = PyObject_CallFunctionObjArgs
(format_exception, type, value, traceback, NULL); (format_exception, type, value, traceback, NULL);
PyErr_Print(); }
if (pylines == NULL) { if (pylines == NULL) {
excval = val("Error calling traceback.format_exception"); excval = val("Error calling traceback.format_exception");
PyErr_Print();
} else { } else {
PyObject *newline = PyUnicode_FromString("\n"); PyObject *newline = PyUnicode_FromString("\n");
PyObject *pystr = PyUnicode_Join(newline, pylines); PyObject *pystr = PyUnicode_Join(newline, pylines);
@ -42,12 +55,13 @@ val pythonExcToJs() {
Py_DECREF(tbmod); Py_DECREF(tbmod);
} }
val Error = val::global("Error"); val exc = val::global("Error").new_(excval);
val exc = Error.new_(excval);
Py_DECREF(type); Py_DECREF(type);
Py_DECREF(value); Py_DECREF(value);
Py_DECREF(traceback); Py_XDECREF(traceback);
PyErr_Clear();
return exc; return exc;
} }