1 /*
2 * Copyright (c) 2024 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 "napi_error.h"
17
18 #include "power_common.h"
19 #include "battery_log.h"
20
21 namespace OHOS {
22 namespace PowerMgr {
23 std::map<BatteryError, std::string> NapiError::errorTable_ = {
24 {BatteryError::ERR_CONNECTION_FAIL, "Connecting to the service failed."},
25 {BatteryError::ERR_PERMISSION_DENIED, "Permission is denied" },
26 {BatteryError::ERR_SYSTEM_API_DENIED, "System permission is denied" },
27 {BatteryError::ERR_PARAM_INVALID, "Invalid input parameter." }
28 };
29
GetNapiError(napi_env & env) const30 napi_value NapiError::GetNapiError(napi_env& env) const
31 {
32 napi_value napiError;
33 if (!IsError()) {
34 napi_get_undefined(env, &napiError);
35 return napiError;
36 }
37
38 std::string msg;
39 auto item = errorTable_.find(code_);
40 if (item != errorTable_.end()) {
41 msg = item->second;
42 }
43 napi_value napiMsg;
44 NAPI_CALL(env, napi_create_string_utf8(env, msg.c_str(), msg.size(), &napiMsg));
45 NAPI_CALL(env, napi_create_error(env, nullptr, napiMsg, &napiError));
46
47 napi_value napiCode;
48 NAPI_CALL(env, napi_create_int32(env, static_cast<int32_t>(code_), &napiCode));
49
50 napi_set_named_property(env, napiError, "code", napiCode);
51 napi_set_named_property(env, napiError, "message", napiMsg);
52
53 BATTERY_HILOGW(COMP_FWK, "throw error code: %{public}d, msg: %{public}s,",
54 static_cast<int32_t>(code_), msg.c_str());
55 return napiError;
56 }
57
ThrowError(napi_env & env,BatteryError code)58 napi_value NapiError::ThrowError(napi_env& env, BatteryError code)
59 {
60 Error(code);
61 napi_value error = GetNapiError(env);
62 RETURN_IF_WITH_RET(error == nullptr, nullptr);
63 napi_throw(env, error);
64 return nullptr;
65 }
66 } // namespace PowerMgr
67 } // namespace OHOS
68