Skip to content

Is it possible to use exception handler with insert table with block? #460

Open

Description

@sabudilovskiy

As far as I can see from the API, using an exception handler is only possible in clickhouse::Query and clickhouse::Block cannot be used there, so it is unclear whether there are ways for client.insert() to work with it.

Activity

  1. sabudilovskiy commented on Feb 2, 2026

    @sabudilovskiy
    Author

    P.s. Basically, all I'm trying to do is make connection issues in my backend a little more attractive. I think it's wrong that std::system_error is thrown when trying to connect instead of something like clickhouse::ConnectionError. Any plans to change this?

  2. polyglotAI-bot commented on Nov 18, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — maintainer decision
    The first question has an answer from the code (below). A maintainer must answer the second question: will connection errors get a library exception type instead of std::system_error? If no such change is planned, the issue can be closed as answered.

    Analysis: OnException runs only for a Query that you give to Execute or Select (client.cpp:370 takes the handlers from that query). Insert(table, block) (client.h:316-317) makes its own Query with no handlers, and BeginInsert(const Query&) throws ValidationError when the query has a handler (client.cpp:533, case 2). With the default rethrow_exceptions = true (client.h:97), a server error during Insert throws clickhouse::ServerException with the server code in GetCode() (case 1): put try/catch around Insert, and call ResetConnection() before a retry (README, "Retries"). Connect errors come from the socket layer as std::system_error (base/socket.cpp:228, :254, :256, name resolution :290; cases 4 and 5), and exceptions.h has no connection error class; because clickhouse::Error (exceptions.h:10) and std::system_error both derive from std::runtime_error, one catch (const std::runtime_error&) handles both. Do not set rethrow_exceptions = false for inserts: then Insert returns normally although the server rejected the data (case 3, 0 rows stored), because EndInsert accepts an Exception packet as the end of the response (client.cpp:587); this looks like a separate defect (compare #406).

    Reproduction: complete program and output
    #include <clickhouse/client.h>
    
    #include <cstdlib>
    #include <iostream>
    #include <memory>
    #include <string>
    #include <system_error>
    
    using namespace clickhouse;
    
    static std::string Env(const char* name, const char* def) {
        const char* v = std::getenv(name);
        return v ? v : def;
    }
    
    static ClientOptions Options(bool rethrow) {
        return ClientOptions()
            .SetHost(Env("CLICKHOUSE_HOST", "localhost"))
            .SetPort(std::stoi(Env("CLICKHOUSE_PORT", "9000")))
            .SetRethrowException(rethrow);
    }
    
    // One row with x = 0. The table has CONSTRAINT x > 0, so the server rejects the data.
    static Block BadBlock() {
        Block block;
        auto x = std::make_shared<ColumnUInt32>();
        x->Append(0);
        block.AppendColumn("x", x);
        return block;
    }
    
    static size_t CountRows(Client& client) {
        size_t rows = 0;
        client.Select("SELECT count() FROM triage_460", [&](const Block& b) {
            if (b.GetRowCount() > 0) rows = b[0]->As<ColumnUInt64>()->At(0);
        });
        return rows;
    }
    
    int main() {
        {
            Client setup(Options(true));
            setup.Execute("DROP TABLE IF EXISTS triage_460");
            setup.Execute("CREATE TABLE triage_460 (x UInt32, CONSTRAINT positive CHECK x > 0) ENGINE = Memory");
        }
    
        // Case 1: Insert(table, block) with the default rethrow_exceptions = true.
        try {
            Client client(Options(true));
            client.Insert("triage_460", BadBlock());
            std::cout << "case 1 Insert, rethrow=true: returned normally\n";
        } catch (const ServerException& e) {
            std::cout << "case 1 Insert, rethrow=true: clickhouse::ServerException code=" << e.GetCode() << "\n";
        } catch (const std::exception& e) {
            std::cout << "case 1 Insert, rethrow=true: other exception: " << e.what() << "\n";
        }
    
        // Case 2: BeginInsert with a Query that has an OnException handler.
        try {
            Client client(Options(true));
            Query query("INSERT INTO triage_460 VALUES");
            query.OnException([](const Exception& e) { std::cout << "  handler called, code=" << e.code << "\n"; });
            client.BeginInsert(query);
            std::cout << "case 2 BeginInsert(Query with OnException): accepted\n";
        } catch (const ValidationError& e) {
            std::cout << "case 2 BeginInsert(Query with OnException): clickhouse::ValidationError: " << e.what() << "\n";
        }
    
        // Case 3: Insert(table, block) with rethrow_exceptions = false.
        try {
            Client client(Options(false));
            client.Insert("triage_460", BadBlock());
            std::cout << "case 3 Insert, rethrow=false: returned normally, rows in table = " << CountRows(client) << "\n";
        } catch (const std::exception& e) {
            std::cout << "case 3 Insert, rethrow=false: exception: " << e.what() << "\n";
        }
    
        // Case 4: connect to a port where no server listens.
        try {
            Client client(ClientOptions().SetHost(Env("CLICKHOUSE_HOST", "localhost")).SetPort(1).SetSendRetries(1));
            std::cout << "case 4 connect: connected\n";
        } catch (const Error& e) {
            std::cout << "case 4 connect: clickhouse::Error: " << e.what() << "\n";
        } catch (const std::system_error& e) {
            std::cout << "case 4 connect: std::system_error code=" << e.code().value()
                      << " category=" << e.code().category().name() << " what=" << e.what()
                      << " is std::runtime_error=" << (dynamic_cast<const std::runtime_error*>(&e) != nullptr) << "\n";
        }
    
        // Case 5: connect to a host name that does not resolve.
        try {
            Client client(ClientOptions().SetHost("no-such-host.invalid").SetPort(9000).SetSendRetries(1));
            std::cout << "case 5 resolve: connected\n";
        } catch (const Error& e) {
            std::cout << "case 5 resolve: clickhouse::Error: " << e.what() << "\n";
        } catch (const std::system_error& e) {
            std::cout << "case 5 resolve: std::system_error category=" << e.code().category().name() << " what=" << e.what() << "\n";
        }
    
        Client cleanup(Options(true));
        cleanup.Execute("DROP TABLE IF EXISTS triage_460");
        return 0;
    }

    Output on master (58453c2), ClickHouse 26.10.4.207, clang 18, default 2.x build options:

    case 1 Insert, rethrow=true: clickhouse::ServerException code=469
    case 2 BeginInsert(Query with OnException): clickhouse::ValidationError: Query callbacks are not supported in BeginInsert
    case 3 Insert, rethrow=false: returned normally, rows in table = 0
    case 4 connect: std::system_error code=111 category=system what=fail to connect: Connection refused is std::runtime_error=1
    case 5 resolve: std::system_error category=getaddrinfoError what=Temporary failure in name resolution
    exit=0
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions