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 #include "error_util.h"
16
17 #include <string>
18 #include <unordered_map>
19
20 namespace OHOS {
21 namespace Global {
22 namespace I18n {
23 static const std::unordered_map<int32_t, std::string> ErrorCodeToMsg {
24 {I18N_NO_PERMISSION,
25 "Permission verification failed. The application does not have the permission required to call the API."},
26 {I18N_NOT_SYSTEM_APP,
27 "Permission verification failed. A non-system application calls a system API."},
28 {I18N_NOT_VALID, "Invalid parameter"},
29 {I18N_NOT_FOUND, "Parameter error"},
30 {I18N_OPTION_NOT_VALID, "Invalid option name"}
31 };
32
NapiThrow(napi_env env,int32_t errCode,const std::string & valueName,const std::string & valueContent,bool throwError)33 void ErrorUtil::NapiThrow(napi_env env, int32_t errCode, const std::string& valueName,
34 const std::string& valueContent, bool throwError)
35 {
36 if (!throwError) {
37 return;
38 }
39 napi_value code = nullptr;
40 napi_create_string_latin1(env, std::to_string(errCode).c_str(), NAPI_AUTO_LENGTH, &code);
41
42 napi_value message = nullptr;
43 auto iter = ErrorCodeToMsg.find(errCode);
44 std::string errMsg = iter != ErrorCodeToMsg.end() ? iter->second : "";
45 std::string allErrMsg;
46
47 if (errCode == I18N_NO_PERMISSION || errCode == I18N_NOT_SYSTEM_APP) {
48 allErrMsg = errMsg;
49 } else if (errCode == I18N_NOT_VALID) {
50 allErrMsg = errMsg + ", the " + valueName + " must be " + valueContent + ".";
51 } else if (valueContent.length() == 0) {
52 allErrMsg = errMsg + ", the " + valueName + " cannot be empty.";
53 } else {
54 allErrMsg = errMsg + ", the type of " + valueName + " must be " + valueContent + ".";
55 }
56
57 napi_create_string_latin1(env, allErrMsg.c_str(), NAPI_AUTO_LENGTH, &message);
58
59 napi_value error = nullptr;
60 napi_create_error(env, code, message, &error);
61 napi_throw(env, error);
62 }
63 } // namespace I18n
64 } // namespace Global
65 } // namespace OHOS