3 ms·
I am writing some C++ code for a web application, and there I am handling errors via exception. There are two broad types of exceptions, one that is internal an
by _448 5y ago
I am writing some C++ code for a web application, and there I am handling errors via exception. There are two broad types of exceptions, one that is internal and one that needs to be reported to the user. Following is how I an handling the errors, please could you all suggest a better approach if my approach is sub-optimal designwise?
// Base class
HandleRequest(req, res)
{
try {
try {
post_processing(req, res) // implemented by derived class
process_request(req, res) // implemented by derived class
pre_processing(req, res) // implemented by derived class
} catch(send_to_user_exception) {
send_error_to_user(send_to_user_exception.what()) // implemented by derived class
}
} catch(internal_exception) {
log_error(internal_exception.what())
send_internal_error_to_user(internal_exception.what()) // implemented by derived class
} catch(unknown_exception) {
log_error(unkown_exception.what())
send_internal_error_to_user(unkown_exception.what()) // implemented by derived class
}
}
// Each request type is handled by its corresponding derived class and implements the following methods of the base class.
post_processing(req, res) // will throw exceptions of type send_to_user_exception and internal_exception
process_request(req, res) // will throw exceptions of type send_to_user_exception and internal_exception
pre_processing(req, res) // will throw exceptions of type send_to_user_exception and internal_exception
send_error_to_user(error)
send_internal_error_to_user(error)
- blub 5y agoThere's nothing wrong design-wise with your approach, IMO. I've seen several people (including very well-known C++ personalities) argue that exceptions should be used for X and error codes for Y, but this is just convention. C++-wise, you probably want to catch std::exception and "..." too. Finally, you said that there's two types of exceptions and only one of them is supposed to be reported to the user, but in your code you seem to report everything to the user. You should edit your message to clarify what you meant.
- _448 5y ago> C++-wise, you probably want to catch std::exception and "..." too. Yeah, the "unknown_exception" in the above pseudocode represents that :) > Finally, you said that there's two types of exceptions and only one of them is supposed to be reported to the user, but in your code you seem to report everything to the user. You should edit your message to clarify what you meant. Yeah, only one will be reported because only one exception handler will be called. So the internal error will be reported to the user as "internal error" and some internal code that the user can report back to me if they want to. The other error is user error. So broadly there are only two categories of errors.