1 /*
2  * Copyright (c) 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 OHOS_FILEMGMT_BACKUP_B_EXCEP_UTILES_H
17 #define OHOS_FILEMGMT_BACKUP_B_EXCEP_UTILES_H
18 
19 #include <exception>
20 
21 #include "b_error/b_error.h"
22 #include "filemgmt_libhilog.h"
23 
24 namespace OHOS::FileManagement::Backup {
25 class BExcepUltils {
26 public:
27     /**
28      * @brief 异常捕获
29      *
30      * @param callBack 回调
31      * @return ErrCode 错误码
32      */
ExceptionCatcherLocked(std::function<ErrCode (void)> callBack)33     static ErrCode ExceptionCatcherLocked(std::function<ErrCode(void)> callBack)
34     {
35         try {
36             return callBack();
37         } catch (const BError &e) {
38             return e.GetCode();
39         } catch (const std::exception &e) {
40             HILOGE("Catched an unexpected low-level exception %{public}s", e.what());
41             return EPERM;
42         } catch (...) {
43             HILOGE("Unexpected exception");
44             return EPERM;
45         }
46     }
47 
48     /**
49      * @brief 检查 AbilityInfo 是否有效
50      *
51      * @param AbilityInfo
52      * @param code 错误码
53      * @param msg 错误信息
54      * @return 无
55      */
56     template <class T>
57     static void BAssert(const T &t, const BError::Codes &code, const std::string_view msg = "")
58     {
59         if (!t) {
60             if (msg.empty()) {
61                 throw BError(code);
62             } else {
63                 throw BError(code, msg);
64             }
65         }
66     }
67 
68     /**
69      * @brief 校验路径
70      *
71      * @param path
72      * @param isExtension
73      */
74     static void VerifyPath(const std::string_view &path, bool isExtension = false);
75 
76     /**
77      * @brief 获取规范化后的绝对路径
78      *
79      * @param path 路径
80      * @return std::string 返回绝对路径
81      */
82     static std::string Canonicalize(const std::string_view &path);
83 };
84 } // namespace OHOS::FileManagement::Backup
85 #endif // OHOS_FILEMGMT_BACKUP_B_EXCEP_UTILES_H