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 #ifndef UTIL_NAPI_ERROR_H
17 #define UTIL_NAPI_ERROR_H
18 
19 #include <map>
20 #include <string>
21 
22 #include "napi/native_api.h"
23 #include "napi/native_node_api.h"
24 
25 #include "securec.h"
26 #include "utils/log.h"
27 
28 #include "util_napi.h"
29 
30 namespace OHOS {
31 namespace MMI {
32 const std::string ERR_CODE = "code";
33 struct NapiError {
34     int32_t errorCode;
35     std::string msg;
36 };
37 
38 enum NapiErrorCode : int32_t {
39     OTHER_ERROR = -1,
40     COMMON_PERMISSION_CHECK_ERROR = 201,
41     COMMON_PARAMETER_ERROR = 401,
42     COMMON_USE_SYSAPI_ERROR = 202,
43     COMMON_CAPABILITY_NOT_SUPPORTED = 801,
44 };
45 
46 const std::map<int32_t, NapiError> NAPI_ERRORS = {
47     { COMMON_PERMISSION_CHECK_ERROR,
48         { COMMON_PERMISSION_CHECK_ERROR, "Permission denied. An attempt was made to %s forbidden by permission:%s." } },
49     { COMMON_PARAMETER_ERROR, { COMMON_PARAMETER_ERROR, "Parameter error. The type of %s must be %s." } },
50 };
51 
52 #define THROWERR_CUSTOM(env, code, msg) \
53     do { \
54         napi_value businessError = nullptr; \
55         napi_value errorCode = nullptr; \
56         napi_value errorMsg = nullptr; \
57         napi_create_int32(env, code, &errorCode); \
58         napi_create_string_utf8(env, std::string(msg).c_str(), NAPI_AUTO_LENGTH, &errorMsg); \
59         napi_create_error(env, nullptr, errorMsg, &businessError); \
60         napi_set_named_property(env, businessError, ERR_CODE.c_str(), errorCode); \
61         napi_throw(env, businessError); \
62     } while (0)
63 
64 #define THROWERR_API9(env, code, param1, param2) \
65     do { \
66         MMI_HILOGE("ErrorCode:%{public}s", (#code)); \
67         NapiError codeMsg; \
68         if (UtilNapiError::GetApiError(code, codeMsg)) { \
69             char buf[300]; \
70             if (sprintf_s(buf, sizeof(buf), codeMsg.msg.c_str(), param1, param2) > 0) { \
71                 THROWERR_CUSTOM(env, code, buf); \
72             } else { \
73                 MMI_HILOGE("Failed to convert string type to char type"); \
74             } \
75         } \
76     } while (0)
77 namespace UtilNapiError {
78 bool GetApiError(int32_t code, NapiError& codeMsg);
79 } // namespace UtilNapiError
80 } // namespace MMI
81 } // namespace OHOS
82 #endif // UTIL_NAPI_ERROR_H
83