@@ -155,6 +155,31 @@ void installConsoleBindings(
155155 2 );
156156}
157157
158+ // If a function body might throw C++ exceptions other than
159+ // jsi::JSError from Hermes, it should be wrapped in this form:
160+ //
161+ // return maybeCatchException([&] { body })
162+ //
163+ // This will execute body; if exceptions are enabled, this execution
164+ // will be wrapped in a try/catch that catches those exceptions, report it then
165+ // exit.
166+ namespace {
167+ template <typename F>
168+ auto maybeCatchException (const F &f) -> decltype(f()) {
169+ #if defined(HERMESVM_EXCEPTION_ON_OOM) || defined(HERMESVM_TIMELIMIT)
170+ try {
171+ return f ();
172+ } catch (const std::exception &ex) {
173+ // Report thrown exception and exit the process with failure code.
174+ llvm::errs () << ex.what ();
175+ exit (1 );
176+ }
177+ #else // HERMESVM_EXCEPTION_ON_OOM || HERMESVM_TIMELIMIT
178+ return f ();
179+ #endif
180+ }
181+ } // namespace
182+
158183// / Executes the HBC bytecode provided in HermesVM.
159184// / \return true on success, false on error.
160185bool executeHBCBytecode (
@@ -207,12 +232,14 @@ bool executeHBCBytecode(
207232 vm::SamplingProfiler::getInstance ()->enable ();
208233 }
209234
210- llvm::StringRef sourceURL{};
211- auto status = runtime->runBytecode (
212- std::move (bytecode),
213- flags,
214- sourceURL,
215- runtime->makeNullHandle <vm::Environment>());
235+ vm::CallResult<vm::HermesValue> status = maybeCatchException ([&] {
236+ llvm::StringRef sourceURL{};
237+ return runtime->runBytecode (
238+ std::move (bytecode),
239+ flags,
240+ sourceURL,
241+ runtime->makeNullHandle <vm::Environment>());
242+ });
216243
217244 if (options.runtimeConfig .getEnableSampleProfiling ()) {
218245 auto profiler = vm::SamplingProfiler::getInstance ();
0 commit comments