Skip to content
Repos

DevPlaceApp

C++ 1.0 KB41 lines Opens in site

Directory Raw Download

#pragma once
// Spec: SPEC.md FR-NET-04 (error mapping). One error type for every async call.
#include <optional>
#include <string>
#include <utility>
#include <variant>

namespace dp {

struct Error {
  enum class Kind { Offline, Timeout, Http, Api, Decode, Cancelled, Unauthorized, Local };

  Kind kind = Kind::Local;
  int status = 0;
  std::string message;
  bool isSpecific = false;

  static Error generic() {
    return Error{Kind::Api, 0, "Something went wrong. Please try again.", false};
  }
  static Error local(std::string text) { return Error{Kind::Local, 0, std::move(text), true}; }
};

template <class T>
class Result {
 public:
  Result(T value) : data_(std::move(value)) {}
  Result(Error error) : data_(std::move(error)) {}

  bool ok() const { return std::holds_alternative<T>(data_); }
  const T& value() const { return std::get<T>(data_); }
  T& value() { return std::get<T>(data_); }
  const Error& error() const { return std::get<Error>(data_); }

 private:
  std::variant<T, Error> data_;
};

struct Unit {};

}  // namespace dp
48.5ms