Skip to content

Commit

Permalink
Exceptions (#14)
Browse files Browse the repository at this point in the history
* can get single line as exception

* returns exceptions now

* remove stream code
  • Loading branch information
fridgerator authored Sep 30, 2019
1 parent 9883105 commit 97c1eb2
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
36 changes: 35 additions & 1 deletion src/main.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#include <sstream>
#include <Python.h>
#include <frameobject.h>
// #include <datetime.h>
#ifdef COMPILER
#undef COMPILER
Expand Down Expand Up @@ -196,9 +198,41 @@ class CallWorker : public Nan::AsyncWorker {

Py_DECREF(pValue);
} else {
std::string error;
PyObject * errOccurred = PyErr_Occurred();
if (errOccurred != NULL) {
PyObject *pType, *pValue, *pTraceback, *pTypeString;
PyErr_Fetch(&pType, &pValue, &pTraceback);
const char * value = PyUnicode_AsUTF8(pValue);
pTypeString = PyObject_Str(pType);
const char * type = PyUnicode_AsUTF8(pTypeString);

PyTracebackObject * tb = (PyTracebackObject *)pTraceback;
std::ostringstream stream;
_frame * frame = tb->tb_frame;

while (frame != NULL) {
int line = PyCode_Addr2Line(frame->f_code, frame->f_lasti);
const char * filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
const char * funcname = PyUnicode_AsUTF8(frame->f_code->co_name);
stream << "File \"" << filename << "\", line " << line << ", in " << funcname << "\n";
stream << type << ": " << value;
frame = frame->f_back;
}

error.append(stream.str());

Py_DecRef(errOccurred);
Py_DecRef(pTypeString);
PyErr_Restore(pType, pValue, pTraceback);
} else {
error.append("Function call failed");
}

Py_DecRef(pFunc);
PyErr_Print();
argv[0] = Nan::Error("Function call failed");

argv[0] = Nan::Error(error.c_str());
}

callback->Call(2, argv);
Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ describe('nodePython', () => {
})

describe('#call', () => {
it('should return the stack trace', done => {
call('causes_runtime_error')
.then(result => console.log('should not see this : ', result))
.catch(err => {
expect(err.message.includes('tools.py')).to.equal(true)
expect(err.message.includes('in causes_runtime_error')).to.equal(true)
expect(err.message.includes('name \'secon\' is not defined')).to.equal(true)
done()
})
})

it('should return the time series data', done => {
call('time_series_data')
.then(result => {
Expand Down
5 changes: 5 additions & 0 deletions test_files/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,8 @@ def return_dict():
def return_tuple():
x = (1, 2, 3)
return x

def causes_runtime_error():
first = 1
second = 2
return first + secon

0 comments on commit 97c1eb2

Please sign in to comment.