Skip to content

How to return a response when an exception is thrown? #1819

Answered by Iamnotagenius
drizzle042 asked this question in Q&A
Discussion options

You must be logged in to vote

Set a custom exception handler before .run() like so:

drogon::app().setExceptionHandler(myExceptionHandler);

Here's how you define one:

void myExceptionHandler(const std::exception& e, 
                        const drogon::HttpRequestPtr& req, 
                        std::function<void (const drogon::HttpResponsePtr &)>&& callback) {
    if (dynamic_cast<const SomeException*>(&e) != nullptr) {
        callback(errorResponse(drogon::k400BadRequest, e.what()));
        return;
    }
    LOG_ERROR << "Unhandled exception: " << e.what();
    callback(errorResponse(drogon::k500InternalServerError, "Unexpected error"));
}

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by drizzle042
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants