From 231223086cef64b71a33ffe5e167b1addfc0fed7 Mon Sep 17 00:00:00 2001 From: M4x1m3 Date: Wed, 15 Jul 2020 11:38:40 +0200 Subject: [PATCH] [mpy] Added passing errors to JS --- python/port/port.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/python/port/port.cpp b/python/port/port.cpp index bc2ee4113..83fe8c910 100644 --- a/python/port/port.cpp +++ b/python/port/port.cpp @@ -7,6 +7,38 @@ #include #include +#ifdef __EMSCRIPTEN__ +#include + +void python_error_start(const char* type) { + EM_ASM({ + Module.___temp_python_error = new Object(); + Module.___temp_python_error["stacktrace"] = new Array(); + Module.___temp_python_error["type"] = Module.UTF8ToString($0); + }, type); +} + +void python_error_add_trace(const char* file, int line, const char* block) { + EM_ASM({ + var temp_obj = new Object(); + temp_obj["file"] = Module.UTF8ToString($0); + temp_obj["line"] = $1; + temp_obj["block"] = Module.UTF8ToString($2); + Module.___temp_python_error.stacktrace.push(temp_obj); + }, file, line, block); +} + +void python_error_end() { + EM_ASM({ + if (typeof Module.onPythonError === "function") { + Module.onPythonError(Module.___temp_python_error); + } + delete Module.___temp_python_error; + }); +} +#endif + + /* py/parsenum.h is a C header which uses C keyword restrict. * It does not exist in C++ so we define it here in order to be able to include * py/parsenum.h header. */ @@ -65,6 +97,10 @@ bool MicroPython::ExecutionEnvironment::runCode(const char * str) { * because we want to print custom information, we copied and modified the * content of mp_obj_print_exception instead of calling it. */ if (mp_obj_is_exception_instance((mp_obj_t)nlr.ret_val)) { +#ifdef __EMSCRIPTEN__ + mp_obj_exception_t* the_exception = (mp_obj_exception_t*) MP_OBJ_TO_PTR((mp_obj_t)nlr.ret_val); + python_error_start(qstr_str(the_exception->base.type->name)); +#endif size_t n, *values; mp_obj_exception_get_traceback((mp_obj_t)nlr.ret_val, &n, &values); if (n > 0) { @@ -74,6 +110,9 @@ bool MicroPython::ExecutionEnvironment::runCode(const char * str) { if (values[i] == 0) { mp_printf(&mp_plat_print, " Last command\n"); } else { +#ifdef __EMSCRIPTEN__ + python_error_add_trace((const char*) qstr_str(values[i]), (int) values[i + 1], (const char*) qstr_str(values[i+2])); +#endif #if MICROPY_ENABLE_SOURCE_LINE mp_printf(&mp_plat_print, " File \"%q\", line %d", values[i], (int)values[i + 1]); #else @@ -90,6 +129,9 @@ bool MicroPython::ExecutionEnvironment::runCode(const char * str) { } } } +#ifdef __EMSCRIPTEN__ + python_error_end(); +#endif } mp_obj_print_helper(&mp_plat_print, (mp_obj_t)nlr.ret_val, PRINT_EXC); mp_print_str(&mp_plat_print, "\n");