While writing the program, I encountered the need to handle multiple errors in one block. The client can return errors that are inherited from more than one class. It is necessary to separately handle errors with status code 4xx and code 5xx. Each error inherits strictly from two known classes and differ only in the class name. I decided that one of the ways to handle this case is to catch one base class and somehow get the second one. What is the safest way to get the second ancestor class from the first?
// begin of external library
class ExceptionWithStatusCode : public std::exception {
int status_code;
};
struct Details {};
class ErrorResponseModel {
Details details;
};
class Response400 : public ExceptionWithStatusCode, ErrorResponseModel {};
class Response401 : public ExceptionWithStatusCode, ErrorResponseModel {};
class Response500 : public ExceptionWithStatusCode, ErrorResponseModel {};
class Response501 : public ExceptionWithStatusCode, ErrorResponseModel {};
// end of external library
int main()
{
try {
do_request();
} catch (const ExceptionWithStatusCode& ex) {
if (ex.status_code < 500) {
// handle 4xx using ErrorResponseModel::details
} else {
// handle 5xx using ErrorResponseModel::details
}
}
return 0;
}