// This program illustrates how one can plug one's error code // enumeration into <code>std::error_code</code> facility. // FILE: flights.h # include <system_error> enum class FlightsErrc { // no 0 NonexistentLocations = 10, // requested airport doesn't exist DatesInThePast, // booking flight for yesterday InvertedDates, // returning before departure NoFlightsFound = 20, // did not find any combination ProtocolViolation = 30, // e.g., bad XML ConnectionError, // could not connect to server ResourceError, // service run short of resources Timeout, // did not respond in time }; namespace std { template <> struct is_error_code_enum<FlightsErrc> : true_type {}; } std::error_code make_error_code(FlightsErrc); // FILE: main.cpp // # include "flights.h" # include <cassert> # include <iostream> int main () { std::error_code ec = FlightsErrc::NoFlightsFound; assert (ec); assert (ec == FlightsErrc::NoFlightsFound); assert (ec != FlightsErrc::InvertedDates); std::cout << ec << std::endl; } // FILE: flights.cpp // # include "flights.h" namespace { // anonymous namespace struct FlightsErrCategory : std::error_category { const char* name() const noexcept override; std::string message(int ev) const override; }; const char* FlightsErrCategory::name() const noexcept { return "flights"; } std::string FlightsErrCategory::message(int ev) const { switch (static_cast<FlightsErrc>(ev)) { case FlightsErrc::NonexistentLocations: return "nonexistent airport name in request"; case FlightsErrc::DatesInThePast: return "request for a date from the past"; case FlightsErrc::InvertedDates: return "requested flight return date before departure date"; case FlightsErrc::NoFlightsFound: return "no filight combination found"; case FlightsErrc::ProtocolViolation: return "received malformed request"; case FlightsErrc::ConnectionError: return "could not connect to server"; case FlightsErrc::ResourceError: return "insufficient resources"; case FlightsErrc::Timeout: return "processing timed out"; default: return "(unrecognized error)"; } } const FlightsErrCategory theFlightsErrCategory {}; } // anonymous namespace std::error_code make_error_code(FlightsErrc e) { return {static_cast<int>(e), theFlightsErrCategory}; }
Advertisements