1 /*
2  * Copyright (c) 2023 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 "devicestatus_napi_error.h"
17 
18 #include <optional>
19 
20 #include "fi_log.h"
21 
22 #undef LOG_TAG
23 #define LOG_TAG "DeviceStatusNapiError"
24 
25 namespace OHOS {
26 namespace Msdp {
27 namespace DeviceStatus {
28 
CreateNapiError(const napi_env & env,int32_t errCode,const std::string & errMessage)29 napi_value CreateNapiError(const napi_env &env, int32_t errCode, const std::string &errMessage)
30 {
31     napi_value businessError = nullptr;
32     napi_value msg = nullptr;
33     napi_value code = nullptr;
34     NAPI_CALL(env, napi_create_int32(env, errCode, &code));
35     NAPI_CALL(env, napi_create_string_utf8(env, errMessage.c_str(), NAPI_AUTO_LENGTH, &msg));
36     napi_create_error(env, nullptr, msg, &businessError);
37     napi_set_named_property(env, businessError, "code", code);
38     return businessError;
39 }
40 
GetErrMsg(int32_t errorCode)41 std::optional <std::string> GetErrMsg(int32_t errorCode)
42 {
43     auto emiter = ERROR_MESSAGES.find(errorCode);
44     if (emiter != ERROR_MESSAGES.end()) {
45         return emiter->second;
46     }
47     FI_HILOGE("Error messages not found");
48     return std::nullopt;
49 }
50 
ThrowErr(const napi_env & env,int32_t errCode,const std::string & printMsg)51 void ThrowErr(const napi_env &env, int32_t errCode, const std::string &printMsg)
52 {
53     FI_HILOGE("printMsg:%{public}s, errCode:%{public}d", printMsg.c_str(), errCode);
54     std::optional<std::string> msg = GetErrMsg(errCode);
55     if (!msg) {
56         FI_HILOGE("errCode:%{public}d is invalid", errCode);
57         return;
58     }
59     napi_value error = CreateNapiError(env, errCode, msg.value());
60     napi_throw(env, error);
61 }
62 } // namespace DeviceStatus
63 } // namespace Msdp
64 } // namespace OHOS
65