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 
CreateBusinessError(const napi_env & env,int32_t errCode,const std::string & errMsg)34 napi_value CreateBusinessError(const napi_env &env, int32_t errCode, const std::string &errMsg)
35 {
36     auto commMsg = GetErrMsgByErrCode(errCode);
37     napi_value result;
38     if (!commMsg.has_value()) {
39         napi_get_undefined(env, &result);
40         USB_HILOGE(MODULE_JS_NAPI, "get error code failed");
41         return result;
42     }
43     std::string cMsg(std::string(commMsg.value()) + errMsg);
44     napi_value message = nullptr;
45     NAPI_CALL(env, napi_create_string_utf8(env, cMsg.c_str(), NAPI_AUTO_LENGTH, &message));
46 
47     napi_value code = nullptr;
48     NAPI_CALL(env, napi_create_int32(env, errCode, &code));
49 
50     napi_value businessError = nullptr;
51     napi_create_error(env, nullptr, message, &businessError);
52     napi_set_named_property(env, businessError, "code", code);
53     return businessError;
54 }
55 
ThrowBusinessError(const napi_env & env,int32_t errCode,const std::string & errMsg)56 void ThrowBusinessError(const napi_env &env, int32_t errCode, const std::string &errMsg)
57 {
58     napi_value businessError = nullptr;
59     businessError = CreateBusinessError(env, errCode, errMsg);
60     napi_throw(env, businessError);
61 }
62 } // namespace USB
63 } // namespace OHOS
64