• 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 #include "n_error.h"
17 
18 #include <cstring>
19 
20 #include "n_val.h"
21 #include "filemgmt_libhilog.h"
22 
23 namespace OHOS {
24 namespace FileManagement {
25 namespace LibN {
26 using namespace std;
27 
NError()28 NError::NError() {}
29 
NError(int ePosix)30 NError::NError(int ePosix) : errno_(ePosix), errMsg_(strerror(errno_)) {}
31 
NError(std::function<std::tuple<uint32_t,std::string> ()> errGen)32 NError::NError(std::function<std::tuple<uint32_t, std::string>()> errGen)
33 {
34     tie(errno_, errMsg_) = errGen();
35 }
36 
operator bool() const37 NError::operator bool() const
38 {
39     return errno_ != ERRNO_NOERR;
40 }
41 
GetNapiErr(napi_env env)42 napi_value NError::GetNapiErr(napi_env env)
43 {
44     napi_value code = NVal::CreateUTF8String(env, to_string(errno_)).val_;
45     napi_value msg = NVal::CreateUTF8String(env, errMsg_).val_;
46 
47     napi_value res = nullptr;
48     napi_status createRes = napi_create_error(env, code, msg, &res);
49     if (createRes) {
50         HILOGE("Failed to create an exception, msg = %{public}s", errMsg_.c_str());
51     }
52     return res;
53 }
54 
ThrowErr(napi_env env,string errMsg)55 void NError::ThrowErr(napi_env env, string errMsg)
56 {
57     napi_value tmp = nullptr;
58     napi_get_and_clear_last_exception(env, &tmp);
59     // Note that ace engine cannot thow errors created by napi_create_error so far
60     napi_status throwStatus = napi_throw_error(env, nullptr, errMsg.c_str());
61     if (throwStatus != napi_ok) {
62         HILOGE("Failed to throw an exception, %{public}d, code = %{public}s", throwStatus, errMsg.c_str());
63     }
64 }
65 
ThrowErr(napi_env env)66 void NError::ThrowErr(napi_env env)
67 {
68     ThrowErr(env, errMsg_);
69 }
70 } // namespace LibN
71 } // namespace FileManagement
72 } // namespace OHOS