|
| 1 | +#include <string> |
| 2 | +#include <vector> |
| 3 | + |
| 4 | +#include "absl/status/status.h" |
| 5 | +#include "absl/strings/str_cat.h" |
| 6 | +#include "third_party/pybind11/include/pybind11/pybind11.h" |
| 7 | +#include "third_party/pybind11/include/pybind11/stl.h" |
| 8 | +#include "pybind11_abseil/compat/status_from_cpp_exc.h" |
| 9 | + |
| 10 | +namespace pybind11_abseil::compat { |
| 11 | + |
| 12 | +namespace { |
| 13 | + |
| 14 | +absl::Status CatchesErrorAlreadySet() { |
| 15 | + pybind11::gil_scoped_acquire gil; |
| 16 | + return CallAndCatchPybind11Exceptions([&]() -> absl::Status { |
| 17 | + PyErr_SetString(PyExc_ValueError, "test error"); |
| 18 | + throw pybind11::error_already_set(); |
| 19 | + }); |
| 20 | +} |
| 21 | + |
| 22 | +absl::Status CatchesBuiltinException() { |
| 23 | + pybind11::gil_scoped_acquire gil; |
| 24 | + return CallAndCatchPybind11Exceptions( |
| 25 | + [&]() -> absl::Status { throw pybind11::value_error("test error 2"); }); |
| 26 | +} |
| 27 | + |
| 28 | +absl::Status CatchesCastError() { |
| 29 | + pybind11::gil_scoped_acquire gil; |
| 30 | + return CallAndCatchPybind11Exceptions([&]() -> absl::Status { |
| 31 | + pybind11::object o = pybind11::int_(1); |
| 32 | + o.cast<std::string>(); |
| 33 | + return absl::OkStatus(); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +absl::Status CatchesStatusNotOk() { |
| 38 | + pybind11::gil_scoped_acquire gil; |
| 39 | + return CallAndCatchPybind11Exceptions([&]() -> absl::Status { |
| 40 | + return absl::ResourceExhaustedError("test error 3"); |
| 41 | + }); |
| 42 | +} |
| 43 | + |
| 44 | +// This function shows that Python and pybind11 exceptions can be caught, and |
| 45 | +// transferred to code that follows Google conventions (i.e. never use C++ |
| 46 | +// exceptions, but use absl::Status instead). |
| 47 | +std::vector<std::string> CollectVariousStatuses() { |
| 48 | + return { |
| 49 | + absl::StrCat(CatchesErrorAlreadySet()), |
| 50 | + absl::StrCat(CatchesBuiltinException()), |
| 51 | + absl::StrCat(CatchesCastError()), |
| 52 | + absl::StrCat(CatchesStatusNotOk()), |
| 53 | + }; |
| 54 | +} |
| 55 | + |
| 56 | +} // namespace |
| 57 | + |
| 58 | +PYBIND11_MODULE(status_from_cpp_exc_test_lib, m) { |
| 59 | + m.def("CollectVariousStatuses", &CollectVariousStatuses); |
| 60 | +} |
| 61 | + |
| 62 | +} // namespace pybind11_abseil::compat |
0 commit comments