• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development 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 "common.h"
17 
18 static const char *TAG = "[jsapi_coercetostring]";
19 
testNapiCoerceToString(napi_env env,napi_callback_info info)20 napi_value testNapiCoerceToString(napi_env env, napi_callback_info info)
21 {
22     // pages/javascript/jsabstractops/napicoercetostring
23     size_t requireArgc = 1;
24     size_t argc = 1;
25     napi_status status;
26     napi_value result;
27     napi_value args[1] = {nullptr};
28     const napi_extended_error_info *extended_error_info;
29 
30     // Get args
31     status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
32     if (status != napi_ok) {
33         napi_throw_error(env, NULL, "Failed to parse arguments");
34         return NULL;
35     }
36 
37     // Call napi_coerce_to_string(), any -> string
38     status = napi_coerce_to_string(env, args[0], &result);
39     if (status != napi_ok) {
40         status = napi_get_last_error_info(env, &extended_error_info);
41         if (status == napi_ok && extended_error_info != NULL) {
42             const char *errorMessage =
43                 extended_error_info->error_message != NULL ? extended_error_info->error_message : "Unknown error";
44 
45             OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "errmsg %{public}s!, engine_err_code %{public}d!.",
46                          errorMessage, extended_error_info->engine_error_code);
47             std::string res = "Failed to coerce to string. em = " + std::string(errorMessage) +
48                               ", eec = " + std::to_string(extended_error_info->engine_error_code) +
49                               ", ec = " + std::to_string(extended_error_info->error_code);
50             napi_throw_error(env, NULL, res.c_str());
51             return NULL;
52         }
53     }
54 
55     // Check if the result is a string
56     napi_valuetype resultType;
57     napi_typeof(env, result, &resultType);
58     if (resultType != napi_string) {
59         std::string res = "Expected a string, got " + std::to_string(resultType);
60         napi_throw_error(env, NULL, res.c_str());
61         return NULL;
62     }
63 
64     return result;
65 }