• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 JS_CONCURRENT_MODULE_COMMON_HELPER_ERROR_HELPER_H
17 #define JS_CONCURRENT_MODULE_COMMON_HELPER_ERROR_HELPER_H
18 
19 #include <ctime>
20 #include <iomanip>
21 #include <iostream>
22 #include <regex>
23 #include <sstream>
24 #include <vector>
25 
26 #include "napi/native_api.h"
27 #include "napi/native_node_api.h"
28 #include "napi_helper.h"
29 #include "native_engine/native_engine.h"
30 
31 namespace Commonlibrary::Concurrent::Common::Helper {
32 class ErrorHelper {
33 public:
34     ErrorHelper() = default;
35     ~ErrorHelper() = default;
36 
37     static napi_value NewError(napi_env env, int32_t errCode, const char* errMessage = nullptr)
38     {
39         std::string errTitle = "";
40         napi_value concurrentError = nullptr;
41 
42         napi_value code = nullptr;
43         napi_create_uint32(env, errCode, &code);
44 
45         napi_value name = nullptr;
46         std::string errName = "BusinessError";
47         switch (errCode) {
48             case ERR_WORKER_INITIALIZATION:
49                 errTitle = "Worker initialization failure, ";
50                 break;
51             case ERR_WORKER_NOT_RUNNING:
52                 errTitle = "Worker instance is not running, ";
53                 break;
54             case ERR_WORKER_UNSUPPORTED:
55                 errTitle = "The invoked API is not supported in workers, ";
56                 break;
57             case ERR_WORKER_SERIALIZATION:
58                 errTitle = "An exception occurred during serialization, ";
59                 break;
60             case ERR_WORKER_INVALID_FILEPATH:
61                 errTitle = "The worker file path is invalid path, ";
62                 break;
63             case ERR_NOT_CONCURRENT_FUNCTION:
64                 errTitle = "The function is not mark as concurrent, ";
65                 break;
66             case ERR_CANCEL_NONEXIST_TASK:
67                 errTitle = "The task does not exist when it is canceled";
68                 break;
69             case ERR_CANCEL_NONEXIST_TASK_GROUP:
70                 errTitle = "The task group does not exist when it is canceled";
71                 break;
72             case ERR_CANCEL_RUNNING_TASK:
73                 errTitle = "The task is executing when it is canceled";
74                 break;
75             case ERR_TRIGGER_NONEXIST_EVENT:
76                 errTitle = "The globalCallObject is not registered";
77                 break;
78             case ERR_CALL_METHOD_ON_BINDING_OBJ:
79                 errTitle = "The method to be called is not callable or is an async method or a generator.";
80                 break;
81             case ERR_GLOBAL_CALL_TIMEOUT:
82                 errTitle = "The global call exceeds the timeout.";
83                 break;
84             case ERR_NOT_IN_TASKPOOL_THREAD:
85                 errTitle = "The function is not called in the taskpool thread";
86                 break;
87             case ERR_NOT_IN_CONCURRENT_FUNCTION:
88                 errTitle = "The function is not called in the concurrent function";
89                 break;
90             case ERR_NOT_REGISTERED:
91                 errTitle = "The callback is not registered on the host side";
92                 break;
93             case ERR_CIRCULAR_DEPENDENCY:
94                 errTitle = "There is a circular dependency";
95                 break;
96             case ERR_INEXISTENT_DEPENDENCY:
97                 errTitle = "The dependency does not exist";
98                 break;
99             case ERR_DELAY_TIME_ERROR:
100                 errTitle = "The delayTime is less than zero";
101                 break;
102             case ERR_IN_BOTH_CLONE_AND_TRANSFER:
103                 errTitle = "Can not set an arraybuffer to both transferList and cloneList";
104                 break;
105             default:
106                 break;
107         }
108         napi_create_string_utf8(env, errName.c_str(), NAPI_AUTO_LENGTH, &name);
109         napi_value msg = nullptr;
110         if (errMessage == nullptr) {
111             napi_create_string_utf8(env, errTitle.c_str(), NAPI_AUTO_LENGTH, &msg);
112         } else {
113             napi_create_string_utf8(env, (errTitle + std::string(errMessage)).c_str(), NAPI_AUTO_LENGTH, &msg);
114         }
115 
116         napi_create_error(env, nullptr, msg, &concurrentError);
117         napi_set_named_property(env, concurrentError, "code", code);
118         napi_set_named_property(env, concurrentError, "name", name);
119         return concurrentError;
120     }
121 
122     static void ThrowError(napi_env env, int32_t errCode, const char* errMessage = nullptr)
123     {
124         napi_value concurrentError = NewError(env, errCode, errMessage);
125         napi_throw(env, concurrentError);
126     }
127 
GetCurrentTimeStamp()128     static std::string GetCurrentTimeStamp()
129     {
130         auto now = std::chrono::system_clock::now();
131         std::time_t currentTimeStamp = std::chrono::system_clock::to_time_t(now);
132         std::tm* timeInfo = std::localtime(&currentTimeStamp);
133         std::stringstream ss;
134         ss << std::put_time(timeInfo, "%Y-%m-%d %X");
135         return ss.str();
136     }
137 
GetErrorFileInfo(const std::string & input)138     static std::string GetErrorFileInfo(const std::string& input)
139     {
140         std::regex pattern("\\((.*?)\\)");
141         std::smatch match;
142         if (std::regex_search(input, match, pattern)) {
143             return match[1].str();
144         }
145         return "";
146     }
147 
SplitErrorFileInfo(const std::string & input,char delimiter,int count)148     static std::vector<std::string> SplitErrorFileInfo(const std::string& input, char delimiter, int count)
149     {
150         std::vector<std::string> result;
151         std::string rawErrorInfo = GetErrorFileInfo(input);
152         if (rawErrorInfo.empty()) {
153             return result;
154         }
155 
156         auto pos = rawErrorInfo.rfind(delimiter);
157         while (pos != std::string::npos && count > 0) {
158             result.push_back(rawErrorInfo.substr(pos + 1));
159             rawErrorInfo = rawErrorInfo.substr(0, pos);
160             pos = rawErrorInfo.rfind(delimiter);
161             count--;
162         }
163         result.push_back(rawErrorInfo);
164         std::reverse(result.begin(), result.end());
165         return result;
166     }
167 
TranslateErrorEvent(napi_env env,napi_value error)168     static napi_value TranslateErrorEvent(napi_env env, napi_value error)
169     {
170         napi_value obj = NapiHelper::CreateObject(env);
171 
172         // add message
173         napi_value msgValue = nullptr;
174         napi_coerce_to_string(env, error, &msgValue);
175         napi_set_named_property(env, obj, "message", msgValue);
176 
177         // add backtrace
178         napi_value stack = NapiHelper::GetNameProperty(env, error, "stack");
179         napi_set_named_property(env, obj, "backtrace", stack);
180 
181         // add timeStamp
182         std::string current = GetCurrentTimeStamp();
183         napi_value timeStamp = nullptr;
184         napi_create_string_utf8(env, current.c_str(), NAPI_AUTO_LENGTH, &timeStamp);
185         napi_set_named_property(env, obj, "timeStamp", timeStamp);
186         char* stackValue = NapiHelper::GetString(env, stack);
187         std::string rawStack = std::string(stackValue);
188         delete[] stackValue;
189         std::vector<std::string> result = SplitErrorFileInfo(rawStack, ':', 2); // 2 : the last two :
190         if (result.size() == 3) { // 3 : the rawStack is divided into three parts by last two :
191             // add filename
192             napi_value filenameValue = nullptr;
193             napi_create_string_utf8(env, result[0].c_str(), NAPI_AUTO_LENGTH, &filenameValue); // 0 : filename
194             napi_set_named_property(env, obj, "filename", filenameValue);
195 
196             // add lineno
197             napi_value lineno = nullptr;
198             napi_create_string_utf8(env, result[1].c_str(), NAPI_AUTO_LENGTH, &lineno); // 1 : lineno
199             napi_set_named_property(env, obj, "lineno", lineno);
200 
201             // add colno
202             napi_value colno = nullptr;
203             napi_create_string_utf8(env, result[2].c_str(), NAPI_AUTO_LENGTH, &colno); // 2 : colno
204             napi_set_named_property(env, obj, "colno", colno);
205         }
206 
207         // add type
208         napi_value eventType = nullptr;
209         napi_create_string_utf8(env, "ErrorEvent", NAPI_AUTO_LENGTH, &eventType);
210         napi_set_named_property(env, obj, "type", eventType);
211 
212         // add error
213         napi_set_named_property(env, obj, "error", error);
214 
215         return obj;
216     }
217 
ObjectToError(napi_env env,napi_value error)218     static napi_value ObjectToError(napi_env env, napi_value error)
219     {
220         napi_value message = NapiHelper::GetNameProperty(env, error, "message");
221         napi_value backtrace = NapiHelper::GetNameProperty(env, error, "backtrace");
222         napi_value businessError = nullptr;
223         napi_create_error(env, nullptr, message, &businessError);
224         napi_set_named_property(env, businessError, "stack", backtrace);
225         napi_set_named_property(env, businessError, "name", message);
226         return businessError;
227     }
228 
229     static const int32_t TYPE_ERROR = 401; // 401 : the parameter type is incorrect
230     static const int32_t ERR_WORKER_INITIALIZATION = 10200003; // 10200003 : worker initialization failure
231     static const int32_t ERR_WORKER_NOT_RUNNING = 10200004; // 10200004 : worker instance is not running
232     static const int32_t ERR_WORKER_UNSUPPORTED = 10200005; // 10200005 : the invoked API is not supported in worker
233     static const int32_t ERR_WORKER_SERIALIZATION = 10200006; // 10200006 : serialize an uncaught exception failed
234     static const int32_t ERR_WORKER_INVALID_FILEPATH = 10200007; // 10200007 : the worker file path is invalid path
235     static const int32_t ERR_NOT_CONCURRENT_FUNCTION = 10200014; // 10200014 : the function is not mark as concurrent
236     static const int32_t ERR_CANCEL_NONEXIST_TASK = 10200015; // 10200015 : the task does not exist when it is canceled
237     static const int32_t ERR_CANCEL_RUNNING_TASK = 10200016; // 10200016 : the task is executing when it is canceled
238     static const int32_t ERR_CANCEL_NONEXIST_TASK_GROUP = 10200018; // 10200018 : cancel nonexist task group
239     static const int32_t ERR_TRIGGER_NONEXIST_EVENT = 10200019; // 10200019 : The triggered event does not exist
240     // 10200020 : The called method is not callable or async or generator
241     static const int32_t ERR_CALL_METHOD_ON_BINDING_OBJ = 10200020;
242     static const int32_t ERR_GLOBAL_CALL_TIMEOUT = 10200021; // 10200021 : Global call has exceeded the timeout
243     // 10200022 : The function is not called in the taskpool thread
244     static const int32_t ERR_NOT_IN_TASKPOOL_THREAD = 10200022;
245     // 10200023 : The function is not called in the concurrent function
246     static const int32_t ERR_NOT_IN_CONCURRENT_FUNCTION = 10200023;
247     static const int32_t ERR_NOT_REGISTERED = 10200024; // 10200024 : The callback is not registered on the host side
248     // 10200025 : add dependent task to SequenceRunner
249     static const int32_t ERR_ADD_DEPENDENT_TASK_TO_SEQRUNNER = 10200025;
250     static const int32_t ERR_CIRCULAR_DEPENDENCY = 10200026; // 10200026 : There is a circular dependency
251     static const int32_t ERR_INEXISTENT_DEPENDENCY = 10200027; // 10200027: The dependency does not exist
252     static const int32_t ERR_DELAY_TIME_ERROR = 10200028; // 10200028 : The delayTime is less than zero
253     // 10200029 : Obj in both clone array and transfer array
254     static const int32_t ERR_IN_BOTH_CLONE_AND_TRANSFER = 10200029;
255 };
256 } // namespace Commonlibrary::Concurrent::Common::Helper
257 #endif // JS_CONCURRENT_MODULE_COMMON_HELPER_ERROR_HELPER_H