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 #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 #include "securec.h" 25 26 #include "devicestatus_errors.h" 27 #include "util_napi.h" 28 29 namespace OHOS { 30 namespace Msdp { 31 namespace DeviceStatus { 32 const std::string ERR_CODE { "code" }; 33 34 const std::map<int32_t, std::string> NAPI_ERRORS = { 35 { COMMON_PERMISSION_CHECK_ERROR, "Permission denied. An attempt was made to %s forbidden by permission:%s." }, 36 { COMMON_PARAMETER_ERROR, "Parameter error. The type of %s must be %s." }, 37 { COMMON_NOT_ALLOWED_DISTRIBUTED, "Cross-device dragging is not allowed" }, 38 { COOPERATOR_FAIL, "Input device operation failed." }, 39 { COMMON_NOT_SYSTEM_APP, "Non system applications." } 40 }; 41 42 #define THROWERR_CUSTOM(env, code, msg) \ 43 do { \ 44 napi_value businessError = nullptr; \ 45 napi_value errorMsg = nullptr; \ 46 napi_value errorCode = nullptr; \ 47 napi_create_int32(env, code, &errorCode); \ 48 napi_create_string_utf8(env, std::string(msg).c_str(), NAPI_AUTO_LENGTH, &errorMsg); \ 49 napi_create_error(env, nullptr, errorMsg, &businessError); \ 50 napi_set_named_property(env, businessError, ERR_CODE.c_str(), errorCode); \ 51 napi_throw(env, businessError); \ 52 FI_HILOGE("Raising exceptions, errorCode:%{public}d, errorMsg:%{public}s", \ 53 static_cast<int32_t>(code), std::string(msg).c_str()); \ 54 } while (0) 55 56 #define THROWERR(env, code, param1, param2) \ 57 do { \ 58 std::string codeMsg; \ 59 if (UtilNapiError::GetErrorMsg(code, codeMsg)) { \ 60 char buf[300] = { 0 }; \ 61 int32_t ret = sprintf_s(buf, sizeof(buf), codeMsg.c_str(), param1, param2); \ 62 if (ret > 0) { \ 63 THROWERR_CUSTOM(env, code, buf); \ 64 } else { \ 65 FI_HILOGE("Failed to convert string type to char type, error code:%{public}d", \ 66 static_cast<int32_t>(code)); \ 67 } \ 68 } \ 69 } while (0) 70 71 namespace UtilNapiError { 72 bool GetErrorMsg(int32_t code, std::string &codeMsg); 73 void HandleExecuteResult(napi_env env, int32_t errCode, const std::string param1 = "", const std::string param2 = ""); 74 } // namespace UtilNapiError 75 } // namespace DeviceStatus 76 } // namespace Msdp 77 } // namespace OHOS 78 #endif // UTIL_NAPI_ERROR_H 79