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