• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "usb_napi_errors.h"
17 #include <optional>
18 
19 #include "hilog_wrapper.h"
20 #include "napi/native_node_api.h"
21 
22 namespace OHOS {
23 namespace USB {
GetErrMsgByErrCode(int32_t errCode)24 std::optional<std::string_view> GetErrMsgByErrCode(int32_t errCode)
25 {
26     auto obj = ERRCODE_MSG_MAP.find(errCode);
27     if (obj == ERRCODE_MSG_MAP.end()) {
28         USB_HILOGE(MODULE_JS_NAPI, "invalid errCode %{public}d", errCode);
29         return std::nullopt;
30     }
31     return obj->second;
32 }
33 
ThrowBusinessError(const napi_env & env,int32_t errCode,const std::string & errMsg)34 void ThrowBusinessError(const napi_env &env, int32_t errCode, const std::string &errMsg)
35 {
36     auto commMsg = GetErrMsgByErrCode(errCode);
37     if (!commMsg.has_value()) {
38         USB_HILOGE(MODULE_JS_NAPI, "get error code failed");
39         return;
40     }
41     std::string cMsg(std::string(commMsg.value()) + errMsg);
42     napi_value message = nullptr;
43     NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, cMsg.c_str(), NAPI_AUTO_LENGTH, &message));
44 
45     napi_value code = nullptr;
46     NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, errCode, &code));
47 
48     napi_value businessError = nullptr;
49     napi_create_error(env, nullptr, message, &businessError);
50     napi_set_named_property(env, businessError, "code", code);
51     napi_throw(env, businessError);
52 }
53 } // namespace USB
54 } // namespace OHOS