|
| 1 | +/* |
| 2 | + * Copyright (c) 2022-2024, NVIDIA CORPORATION. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +#include "tllmExceptions.h" |
| 18 | +#include "tensorrt_llm/common/tllmException.h" |
| 19 | +#include <nanobind/nanobind.h> |
| 20 | + |
| 21 | +namespace tc = tensorrt_llm::common; |
| 22 | +namespace nb = nanobind; |
| 23 | + |
| 24 | +namespace tensorrt_llm::nanobind::common |
| 25 | +{ |
| 26 | + |
| 27 | +void initExceptionsBindings(nb::module_& m) |
| 28 | +{ |
| 29 | + // Bind the RequestErrorCode enum |
| 30 | + nb::enum_<tc::RequestErrorCode>(m, "RequestErrorCode") |
| 31 | + .value("UNKNOWN_ERROR", tc::RequestErrorCode::kUNKNOWN_ERROR) |
| 32 | + .value("NETWORK_ERROR", tc::RequestErrorCode::kNETWORK_ERROR) |
| 33 | + .export_values(); |
| 34 | + |
| 35 | + // Create the RequestSpecificException Python exception class |
| 36 | + static nb::object request_specific_exc = nb::exception<tc::RequestSpecificException>(m, "RequestSpecificException"); |
| 37 | + |
| 38 | + // Add attributes to the Python exception class |
| 39 | + request_specific_exc.attr("request_id") = nb::none(); |
| 40 | + request_specific_exc.attr("error_code") = nb::none(); |
| 41 | + |
| 42 | + // Register exception translator to convert C++ exceptions to Python |
| 43 | + nb::register_exception_translator( |
| 44 | + [](std::exception_ptr const& p, void*) |
| 45 | + { |
| 46 | + try |
| 47 | + { |
| 48 | + if (p) |
| 49 | + std::rethrow_exception(p); |
| 50 | + } |
| 51 | + catch (const tc::RequestSpecificException& e) |
| 52 | + { |
| 53 | + // Create a Python exception with the request ID and error code information |
| 54 | + nb::object py_exc = nb::cast(e); |
| 55 | + nb::object request_id = nb::cast(e.getRequestId()); |
| 56 | + nb::object error_code = nb::cast(static_cast<uint32_t>(e.getErrorCode())); |
| 57 | + |
| 58 | + // Set additional attributes on the exception |
| 59 | + py_exc.attr("request_id") = request_id; |
| 60 | + py_exc.attr("error_code") = error_code; |
| 61 | + |
| 62 | + PyErr_SetObject(request_specific_exc.ptr(), py_exc.ptr()); |
| 63 | + } |
| 64 | + }); |
| 65 | +} |
| 66 | + |
| 67 | +} // namespace tensorrt_llm::nanobind::common |
0 commit comments