Files
spark/src/lib/api/public/Result.h
T

68 lines
1.6 KiB
C++

#pragma once
#include "ApiException.h"
#include "lib/api/apicore.pb.h"
#include <assert.h>
#include <functional>
#include <memory>
namespace bts {
namespace api {
template <class T> class Result {
std::shared_ptr<T> _t;
ApiError _code;
static const char *error_string(ApiError code) {
switch (code) {
case ApiError::SUCCESS:
return "Success";
case ApiError::NO_SERVER:
return "No server found.";
case ApiError::SERVER_DISCONNECT:
return "Server disconnected.";
case ApiError::MISSING_METHOD:
return "Method not found.";
case ApiError::SERVER_FAULT:
return "Server error.";
case ApiError::UNEXPECTED_RESPONSE:
return "Internal error";
case ApiError::ACCESS_DENIED:
return "Access denied";
default:
return "Unknown error";
}
}
public:
Result(std::shared_ptr<T> &t) : _t(t), _code(ApiError::SUCCESS) {}
Result(std::shared_ptr<T> &&t) : _t(t), _code(ApiError::SUCCESS) {}
Result(ApiError code) : _t(), _code(code) {
assert(_code != ApiError::SUCCESS);
}
#if _MSC_VER
// needed for std::future
Result() : _t(), _code(ApiError::UNEXPECTED_RESPONSE) {}
#endif
std::shared_ptr<T> value() const {
if (success())
return _t;
else
return nullptr;
}
bool success() const { return _code == ApiError::SUCCESS; }
operator bool() const { return success(); }
ApiError code() const { return _code; }
const char *error_message() const { return error_string(_code); }
~Result() {}
};
} // namespace api
} // namespace bts