How to deal with exceptions in IO::Socket::INET?

Viewed 68

Assume there's no application listening at port 12340 in localhost.

Shouldn't the command below print "error" ?

$ raku -e "IO::Socket::INET.new(:host('localhost'), :port(12340)) or die 'error'"
Could not connect socket: No connection could be made because the target machine actively refused it.

  in block <unit> at -e line 1
1 Answers

The current implementation of nqp::connect, the underlying logic to make the connection, throws an X::AdHoc exception. Having IO::Socket::INET.new return a Failure if not able to connect, would make more sense to me indeed.

I've created a Pull Request to create this behaviour.

Until then, you can use the same code change locally:

sub connect($host, $port) {
    CATCH { return .Failure }
    IO::Socket::INET.new(:$host, :$port)
}

connect('localhost', 12340) or die 'error';
Related