How to fail a childChannelInitializer?

here’s a really simple task: reject child channels that lack a valid remoteAddress:

    .childChannelInitializer
{
    (channel:any Channel) -> EventLoopFuture<Void> in

    guard 
    let address:SocketAddress = channel.remoteAddress 
    else
    {
        return channel.close()
    }

    //  continue adding handlers
    ...

but that’s not right, how can you close a channel that has not even been set up yet?

perhaps we can fail the returned EventLoopFuture instead. but the documentation for childChannelInitializer(_:) says that if you do that, that blows up the parent channel, which is not what we want.

i suppose it would be too much to hope for NIO docs that explain what you should do if you just want to abort initialization of the child channel…

That's not what it says. It says the error will be fired there. That's because the error has to be fired somewhere, and it doesn't make much sense to fire it in the child channel, because you just failed its construction.

Returning an error is correct.

2 Likes

gotcha. i thought that firing an error meant that the channel would be closed.

btw, the default implementation for errorCaught has no documentation.

The default implementation just passes it along, as all the default implementations do, but yes we should document that.

By default if you fire an error and nothing catches it, nothing happens. This is why we typically encourage everyone to add error catching handlers to the end of their pipelines (or to use NIOAsyncChannel, which does this for you).

3 Likes