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 
16 #include "sensor_napi_error.h"
17 
18 #include <optional>
19 
20 #undef LOG_TAG
21 #define LOG_TAG "SensorJsAPI"
22 
23 namespace OHOS {
24 namespace Sensors {
CreateBusinessError(const napi_env & env,const int32_t errCode,const std::string & errMessage)25 napi_value CreateBusinessError(const napi_env &env, const int32_t errCode, const std::string &errMessage)
26 {
27     napi_value businessError = nullptr;
28     napi_value code = nullptr;
29     napi_value msg = nullptr;
30     NAPI_CALL(env, napi_create_int32(env, errCode, &code));
31     NAPI_CALL(env, napi_create_string_utf8(env, errMessage.c_str(), NAPI_AUTO_LENGTH, &msg));
32     napi_create_error(env, nullptr, msg, &businessError);
33     napi_set_named_property(env, businessError, "code", code);
34     return businessError;
35 }
36 
GetNapiError(int32_t errorCode)37 std::optional<std::string> GetNapiError(int32_t errorCode)
38 {
39     auto iter = ERROR_MESSAGES.find(errorCode);
40     if (iter != ERROR_MESSAGES.end()) {
41         return iter->second;
42     }
43     return std::nullopt;
44 }
45 
ThrowErr(const napi_env & env,const int32_t errCode,const std::string & printMsg)46 void ThrowErr(const napi_env &env, const int32_t errCode, const std::string &printMsg)
47 {
48     SEN_HILOGE("Message:%{public}s, code:%{public}d", printMsg.c_str(), errCode);
49     auto msg = GetNapiError(errCode);
50     if (!msg) {
51         SEN_HILOGE("ErrCode:%{public}d is invalid", errCode);
52         return;
53     }
54     napi_handle_scope scope = nullptr;
55     napi_open_handle_scope(env, &scope);
56     napi_value error = CreateBusinessError(env, errCode, msg.value());
57     napi_throw(env, error);
58     napi_close_handle_scope(env, scope);
59 }
60 }  // namespace Sensors
61 }  // namespace OHOS