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 #ifndef SERIAL_NAPI
16 #include "usb_napi_errors.h"
17 #else
18 #include "serial_napi_errors.h"
19 #endif
20 #include <optional>
21
22 #include "hilog_wrapper.h"
23 #include "napi/native_node_api.h"
24
25 namespace OHOS {
26 namespace USB {
GetErrMsgByErrCode(int32_t errCode)27 std::optional<std::string_view> GetErrMsgByErrCode(int32_t errCode)
28 {
29 auto obj = ERRCODE_MSG_MAP.find(errCode);
30 if (obj == ERRCODE_MSG_MAP.end()) {
31 USB_HILOGE(MODULE_JS_NAPI, "invalid errCode %{public}d", errCode);
32 return std::nullopt;
33 }
34 return obj->second;
35 }
36
CreateBusinessError(const napi_env & env,int32_t errCode,const std::string & errMsg)37 napi_value CreateBusinessError(const napi_env &env, int32_t errCode, const std::string &errMsg)
38 {
39 auto commMsg = GetErrMsgByErrCode(errCode);
40 napi_value result;
41 if (!commMsg.has_value()) {
42 napi_get_undefined(env, &result);
43 USB_HILOGE(MODULE_JS_NAPI, "get error code failed");
44 return result;
45 }
46 std::string cMsg(std::string(commMsg.value()) + errMsg);
47 napi_value message = nullptr;
48 NAPI_CALL(env, napi_create_string_utf8(env, cMsg.c_str(), NAPI_AUTO_LENGTH, &message));
49
50 napi_value code = nullptr;
51 NAPI_CALL(env, napi_create_int32(env, errCode, &code));
52
53 napi_value businessError = nullptr;
54 napi_create_error(env, nullptr, message, &businessError);
55 napi_set_named_property(env, businessError, "code", code);
56 return businessError;
57 }
58
ThrowBusinessError(const napi_env & env,int32_t errCode,const std::string & errMsg)59 void ThrowBusinessError(const napi_env &env, int32_t errCode, const std::string &errMsg)
60 {
61 napi_value businessError = nullptr;
62 businessError = CreateBusinessError(env, errCode, errMsg);
63 napi_throw(env, businessError);
64 }
65 } // namespace USB
66 } // namespace OHOS
67