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