我有一个非常简单的自定义 error_category ,如下所示。我只是想用“例外”来封装它。因此我为它编写了一个自定义异常类。但是当我运行代码时,我得到垃圾值(每次运行它都会得到不同的值。)。由于错误代码是在异常类中全局定义的,所以应该不会有问题。这是什么原因呢?
#include <string>
#include <system_error>
#include <iostream>
#include <stdexcept>
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
};
class FlightsErrorCategory : public std::error_category {
public:
const char* name() const noexcept override { return "FlightsError"; }
std::string message(int ev) const override {
switch (static_cast<FlightsErrc>(ev)) {
case FlightsErrc::NonexistentLocations: return "Nonexistent locations";
case FlightsErrc::DatesInThePast: return "Dates are in the past";
case FlightsErrc::InvertedDates: return "Inverted dates";
case FlightsErrc::NoFlightsFound: return "No flights found";
case FlightsErrc::ProtocolViolation: return "Protocol violation";
case FlightsErrc::ConnectionError: return "Connection error";
case FlightsErrc::ResourceError: return "Resource error";
case FlightsErrc::Timeout: return "Timeout occurred";
default: return "Unknown Flights error";
}
}
};
inline const std::error_category& flights_error_category() {
static FlightsErrorCategory instance;
return instance;
}
namespace std {
template <> struct is_error_code_enum<FlightsErrc> : true_type {};
}
std::error_code make_error_code(FlightsErrc e) {
return {static_cast<int>(e), flights_error_category()};
}
class FlightsException : public std::exception {
public:
explicit FlightsException(const std::error_code& ec)
: errorCode(ec) {}
const char* what() const noexcept override {
return errorCode.message().c_str();
}
std::error_code code() const noexcept { return errorCode; }
private:
std::error_code errorCode;
};
void flightsServiceFunction(bool simulateError) {
if (simulateError) {
throw FlightsException(FlightsErrc::ConnectionError);
}
}
int main() {
try {
flightsServiceFunction(true);
} catch (const FlightsException& ex) {
std::cout << "FlightException: " << ex.what() << "\n";
} catch (const std::exception& ex) {
std::cerr << "General Exception: " << ex.what() << std::endl;
}
return 0;
}