mooli mooli - 7 months ago 21
Ruby Question

how to get the specific error when TCPServer.open fail in ruby

I try to use rescue, but the error that i get is unclear,
and is same error in different cases (e.g in illegal port and already used port.)

require 'socket'

begin
server = TCPServer.open(33)
rescue => ex
puts "An error of type #{ex.class} happened, message is #{ex.message}"
end


and I get
=> An error of type TypeError happened, message is no implicit conversion of nil into String

Answer

You may mean to use TCPServer.new(33) instead of open(). Open would expect an address to bind, and a block to handle incoming requests, I think.

Regarding the error, it is relatively clear anyway. It is throwing a TypeError which generally means you're giving something the wrong type of input. In this case, you're sending an integer to TCPServer.open() which (according to this example: http://ruby-doc.org/stdlib-2.2.0/libdoc/socket/rdoc/TCPServer.html#method-i-accept) seems to be expecting a string and an integer.

I'm wrong! Sorry. Very strange.