mercredi 20 février 2019

Is there a DRY way to do error handling in callbacks?

I have a networking library that uses asio to do asynchronous reads and writes. I am finding myself writing what I feel is a lot silly boilerplate code:

asio::dispatch(m_strand, [&, cb]() {
          m_buffer = write::startup(m_params);
          write(m_buffer, [&, cb](std::error_code ec, std::size_t len) {
            if (ec) {
              sql_state state;
              cb(ec, state);
              return;
            }
            read([&](std::error_code ec, packet barray) {
              if (ec) {
                sql_state state;
                cb(ec, state);
                return;
              }
              auto packets = parse::split_into_packets(barray);
              uint8_t auth_type{1};
              state = fsm::authentication_request(packets.front(), auth_type);
              if (state) {
                cb(ec, std::move(state));
                return;
              }
            });
          });
        });

Is there a way to abstract away the error handling in an elegant way?

Aucun commentaire:

Enregistrer un commentaire