1 /*
2  * Copyright (c) 2024 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 UPDATE_SERVICE_BUSINESS_ERROR_H
17 #define UPDATE_SERVICE_BUSINESS_ERROR_H
18 
19 #include <string>
20 #include <vector>
21 
22 #include "nlohmann/json.hpp"
23 
24 #include "call_result.h"
25 #include "dupdate_json_utils.h"
26 #include "error_message.h"
27 #include "json_builder.h"
28 
29 namespace OHOS::UpdateEngine {
30 struct BusinessError {
31     std::string message;
32     CallResult errorNum = CallResult::SUCCESS;
33     std::vector<ErrorMessage> data;
34 
BuildBusinessError35     BusinessError &Build(CallResult callResult, const std::string &msg)
36     {
37         errorNum = callResult;
38         message = msg;
39         return *this;
40     }
41 
AddErrorMessageBusinessError42     BusinessError &AddErrorMessage(int32_t errorCode, const std::string &errorMessage)
43     {
44         ErrorMessage errMsg;
45         errMsg.errorCode = errorCode;
46         errMsg.errorMessage = errorMessage;
47         data.push_back(errMsg);
48         return *this;
49     }
50 
to_jsonBusinessError51     friend void to_json(nlohmann::json &jsonObj, const BusinessError &businessError)
52     {
53         jsonObj["message"] = businessError.message;
54         jsonObj["errorNum"] = businessError.errorNum;
55         jsonObj["data"] = businessError.data;
56     }
57 
from_jsonBusinessError58     friend void from_json(const nlohmann::json &jsonObj, BusinessError &businessError)
59     {
60         JsonUtils::GetValueAndSetTo(jsonObj, "message", businessError.message);
61         JsonUtils::GetValueAndSetTo(jsonObj, "data", businessError.data);
62         int32_t errorNumber = static_cast<int32_t>(CallResult::SUCCESS);
63         JsonUtils::GetValueAndSetTo(jsonObj, "errorNum", errorNumber);
64         businessError.errorNum = static_cast<CallResult>(errorNumber);
65     }
66 };
67 } // namespace OHOS::UpdateEngine
68 #endif // UPDATE_SERVICE_BUSINESS_ERROR_H
69