Skip to content
This repository has been archived by the owner on Feb 13, 2024. It is now read-only.

[WIP] Use a enum-based Error type instead of one based on std::string #3772

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.2)
project(TogglDesktop)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Set up automatic resource generation to make Qt development easier
set(CMAKE_INCLUDE_CURRENT_DIR ON)
Expand Down
4 changes: 3 additions & 1 deletion src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ include_directories(

# TogglDesktopLibrary sources
set(LIBRARY_SOURCE_FILES
util/logger.cc
util/error.cc

base_model.cc
batch_update_result.cc
client.cc
Expand All @@ -48,7 +51,6 @@ set(LIBRARY_SOURCE_FILES
feedback.cc
formatter.cc
get_focused_window_linux.cc
error.cc
gui.cc
netconf.cc
https_client.cc
Expand Down
7 changes: 3 additions & 4 deletions src/analytics.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@
#include "settings.h"
#include "urls.h"
#include "user.h"

#include <Poco/Logger.h>
#include "util/logger.h"

namespace toggl {

Expand Down Expand Up @@ -162,7 +161,7 @@ void GoogleAnalyticsEvent::runTask() {
HTTPSClient client;
HTTPSResponse resp = client.Get(req);
if (resp.err != noError) {
Poco::Logger::get("Analytics").error(resp.err);
Logger("Analytics").error(resp.err);
return;
}
}
Expand Down Expand Up @@ -319,7 +318,7 @@ void GoogleAnalyticsSettingsEvent::makeReq() {
HTTPSClient client;
HTTPSResponse resp = client.Get(req);
if (resp.err != noError) {
Poco::Logger::get("Analytics").error(resp.err);
Logger("Analytics").error(resp.err);
return;
}
}
Expand Down
17 changes: 7 additions & 10 deletions src/base_model.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
#include <Poco/Timestamp.h>
#include <Poco/DateTime.h>
#include <Poco/LocalDateTime.h>
#include <Poco/Logger.h>

namespace toggl {

Expand All @@ -22,8 +21,7 @@ bool BaseModel::NeedsPush() const {
// pushed again unless the error is somehow fixed by user.
// We will assume that if user modifies the model, the error
// will go away. But until then, don't push the errored data.
return ValidationError().empty() &&
(NeedsPOST() || NeedsPUT() || NeedsDELETE());
return ValidationError() == noError && (NeedsPOST() || NeedsPUT() || NeedsDELETE());
}

bool BaseModel::NeedsPOST() const {
Expand Down Expand Up @@ -56,7 +54,7 @@ void BaseModel::ClearValidationError() {
SetValidationError(noError);
}

void BaseModel::SetValidationError(const std::string &value) {
void BaseModel::SetValidationError(const error &value) {
if (validation_error_ != value) {
validation_error_ = value;
SetDirty();
Expand Down Expand Up @@ -113,7 +111,7 @@ error BaseModel::LoadFromDataString(const std::string &data_string) {
Json::Value root;
Json::Reader reader;
if (!reader.parse(data_string, root)) {
return error("Failed to parse data string");
return error(error::kFailedToParseData);
}
LoadFromJSON(root["data"]);
return noError;
Expand Down Expand Up @@ -154,8 +152,7 @@ error BaseModel::ApplyBatchUpdateResult(
}

bool BaseModel::userCannotAccessWorkspace(const error &err) const {
return (std::string::npos != std::string(err).find(
kCannotAccessWorkspaceError));
return err == error::kCannotAccessWorkspaceError;
}

std::string BaseModel::batchUpdateRelativeURL() const {
Expand Down Expand Up @@ -183,7 +180,7 @@ std::string BaseModel::batchUpdateMethod() const {
// Convert model JSON into batch update format.
error BaseModel::BatchUpdateJSON(Json::Value *result) const {
if (GUID().empty()) {
return error("Cannot export model to batch update without a GUID");
return error::kExportWithoutGUID;
}

Json::Value body;
Expand All @@ -197,8 +194,8 @@ error BaseModel::BatchUpdateJSON(Json::Value *result) const {
return noError;
}

Poco::Logger &BaseModel::logger() const {
return Poco::Logger::get(ModelName());
Logger BaseModel::logger() const {
return { ModelName() };
}

void BaseModel::SetDirty() {
Expand Down
15 changes: 6 additions & 9 deletions src/base_model.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,10 @@

#include "const.h"
#include "types.h"
#include "util/logger.h"

#include <Poco/Types.h>

namespace Poco {
class Logger;
}

namespace toggl {

class BatchUpdateResult;
Expand All @@ -35,7 +32,7 @@ class TOGGL_INTERNAL_EXPORT BaseModel {
, deleted_at_(0)
, is_marked_as_deleted_on_server_(false)
, updated_at_(0)
, validation_error_("")
, validation_error_(error::kNoError)
, unsynced_(false) {}

virtual ~BaseModel() {}
Expand Down Expand Up @@ -122,8 +119,8 @@ class TOGGL_INTERNAL_EXPORT BaseModel {
void EnsureGUID();

void ClearValidationError();
void SetValidationError(const std::string &value);
const std::string &ValidationError() const {
void SetValidationError(const error &value);
const error &ValidationError() const {
return validation_error_;
}

Expand Down Expand Up @@ -156,7 +153,7 @@ class TOGGL_INTERNAL_EXPORT BaseModel {
error BatchUpdateJSON(Json::Value *result) const;

protected:
Poco::Logger &logger() const;
Logger logger() const;

bool userCannotAccessWorkspace(const toggl::error &err) const;

Expand All @@ -176,7 +173,7 @@ class TOGGL_INTERNAL_EXPORT BaseModel {

// If model push to backend results in an error,
// the error is attached to the model for later inspection.
std::string validation_error_;
error validation_error_;

// Flag is set only when sync fails.
// Its for viewing purposes only. It should not
Expand Down
28 changes: 12 additions & 16 deletions src/batch_update_result.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,19 @@

#include "base_model.h"

#include <Poco/Logger.h>

namespace toggl {

error BatchUpdateResult::Error() const {
if (StatusCode >= 200 && StatusCode < 300) {
return noError;
}
if ("null" != Body) {
return Body;
return error::REMOVE_LATER_BATCH_UPDATE_ERROR;
}
std::stringstream ss;
ss << "Request failed with status code "
<< StatusCode;
return ss.str();
return error::REMOVE_LATER_BATCH_UPDATE_ERROR;
}

std::string BatchUpdateResult::String() const {
Expand Down Expand Up @@ -56,25 +54,21 @@ void BatchUpdateResult::ProcessResponseArray(
poco_check_ptr(models);
poco_check_ptr(errors);

Poco::Logger &logger = Poco::Logger::get("BatchUpdateResult");
for (std::vector<BatchUpdateResult>::const_iterator it = results->begin();
it != results->end();
++it) {
BatchUpdateResult result = *it;

logger.debug(result.String());
logger().debug(result.String());

if (result.GUID.empty()) {
logger.error("Batch update result has no GUID");
logger().error("Batch update result has no GUID");
continue;
}

BaseModel *model = (*models)[result.GUID];
if (!model) {
std::stringstream ss;
ss << "Server response includes a model we don't have! GUID="
<< result.GUID;
logger.warning(ss.str());
logger().warning("Server response includes a model we don't have! GUID=", result.GUID);
continue;
}
error err = model->ApplyBatchUpdateResult(&result);
Expand All @@ -85,27 +79,29 @@ void BatchUpdateResult::ProcessResponseArray(
}
}

Logger BatchUpdateResult::logger() {
return { "BatchUpdateResult" };
}

error BatchUpdateResult::ParseResponseArray(
const std::string &response_body,
std::vector<BatchUpdateResult> *responses) {

poco_check_ptr(responses);

Poco::Logger &logger = Poco::Logger::get("BatchUpdateResult");

// There seem to be cases where response body is 0.
// Must investigate further.
if (response_body.empty()) {
logger.warning("Response is empty!");
logger().warning("Response is empty!");
return noError;
}

logger.debug(response_body);
logger().debug(response_body);

Json::Value root;
Json::Reader reader;
if (!reader.parse(response_body, root)) {
return error("error parsing batch update response");
return error::kFailedToParseData;
}

for (unsigned int i = 0; i < root.size(); i++) {
Expand Down
5 changes: 5 additions & 0 deletions src/batch_update_result.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <map>

#include "types.h"
#include "util/logger.h"

#include <json/json.h> // NOLINT

Expand Down Expand Up @@ -43,6 +44,10 @@ class TOGGL_INTERNAL_EXPORT BatchUpdateResult {
std::vector<BatchUpdateResult> * const results,
std::map<std::string, BaseModel *> *models,
std::vector<error> *errors);

private:
static Logger logger();

};

} // namespace toggl
Expand Down
8 changes: 3 additions & 5 deletions src/client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ bool Client::ResolveError(const toggl::error &err) {
SetName(Name() + " 1");
return true;
}
if (err.find(kClientNameAlreadyExists) != std::string::npos) {
if (err == error::kClientNameAlreadyExists) {
// remove duplicate from db
MarkAsDeletedOnServer();
return true;
Expand All @@ -77,13 +77,11 @@ bool Client::ResolveError(const toggl::error &err) {
}

bool Client::nameHasAlreadyBeenTaken(const error &err) {
return (std::string::npos != std::string(err).find(
"Name has already been taken"));
return err == error::kNameAlreadyTaken;
}

bool Client::ResourceCannotBeCreated(const toggl::error &err) const {
return (std::string::npos != std::string(err).find(
"cannot add or edit clients in workspace"));
return err == error::kCannotModifyWorkspaceData;
}

} // namespace toggl
51 changes: 0 additions & 51 deletions src/const.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,57 +45,6 @@
#define kContentTypeMultipartFormData "multipart/form-data"
#define kContentTypeApplicationJSON "application/json"

// Data validation errors
#define kOverMaxDurationError "Max allowed duration per 1 time entry is 999 hours"
#define kMaxTagsPerTimeEntryError "Tags are limited to 50 per task"
#define kInvalidStartTimeError "Start time year must be between 2006 and 2030"
#define kInvalidStopTimeError "Stop time year must be between 2006 and 2030"
#define kInvalidDateError "Date year must be between 2006 and 2030"
#define kStartNotBeforeStopError "Stop time must be after start time"
#define kMaximumDescriptionLengthError "Maximum length for description (3000 chars) exceeded"

#define kCheckYourSignupError "Signup failed - please check your details. The e-mail might be already taken." // NOLINT
#define kEndpointGoneError "The API endpoint used by this app is gone. Please contact Toggl support!" // NOLINT
#define kForbiddenError "Invalid e-mail or password!"
#define kUnsupportedAppError "This version of the app is not supported any more. Please visit Toggl website to download a supported app." // NOLINT
#define kUnauthorizedError "Unauthorized! Please login again."
#define kCannotConnectError "Cannot connect to Toggl"
#define kCannotSyncInTestEnv "Cannot sync in test env"
#define kBackendIsDownError "Backend is down"
#define kBadRequestError "Data that you are sending is not valid/acceptable"
#define kRequestIsNotPossible "Request is not possible"
#define kPaymentRequiredError "Requested action allowed only for Non-Free workspaces. Please upgrade!" // NOLINT
#define kCannotAccessWorkspaceError "cannot access workspace"
#define kEmailNotFoundCannotLogInOffline "Login failed. Are you online?" // NOLINT
#define kInvalidPassword "Invalid password"
#define kCannotEstablishProxyConnection "Cannot establish proxy connection"
#define kCertificateVerifyFailed "certificate verify failed"
#define kCheckYourProxySetup "Check your proxy setup"
#define kCheckYourFirewall "Check your firewall"
#define kProxyAuthenticationRequired "Proxy Authentication Required"
#define kCertificateValidationError "Certificate validation error"
#define kUnacceptableCertificate "Unacceptable certificate from www.toggl.com"
#define kCannotUpgradeToWebSocketConnection "Cannot upgrade to WebSocket connection" // NOLINT
#define kSSLException "SSL Exception"
#define kRateLimit "Too many requests, sync delayed by 1 minute"
#define kCannotWriteFile "Cannot write file"
#define kIsSuspended "is suspended"
#define kRequestToServerFailedWithStatusCode403 "Request to server failed with status code: 403" // NOLINT
#define kMissingWorkspaceID "Missing workspace ID"
#define kCannotContinueDeletedTimeEntry "Cannot continue deleted time entry"
#define kCannotDeleteDeletedTimeEntry "Cannot delete deleted time entry"
#define kErrorRuleAlreadyExists "rule already exists"
#define kPleaseSelectAWorkspace "Please select a workspace"
#define kClientNameMustNotBeEmpty "Client name must not be empty"
#define kProjectNameMustNotBeEmpty "Project name must not be empty"
#define kProjectNameAlready "Project name already"
#define kProjectNameAlreadyExists "Project name already exists"
#define kClientNameAlreadyExists "Client name already exists"
#define kDatabaseDiskMalformed "The database disk image is malformed"
#define kMissingWS "You no longer have access to your last workspace"
#define kOutOfDatePleaseUpgrade "Your version of Toggl Desktop is out of date, please upgrade!"
#define kThisEntryCantBeSavedPleaseAdd "This entry can't be saved - please add"

#define kModelAutotrackerRule "autotracker_rule"
#define kModelClient "client"
#define kModelProject "project"
Expand Down
Loading