prewett
prewett

Reputation: 1647

How do I check a specific network error in Go?

I have a server that I am writing, and I want to handle errors from conn.Read(). Specifically, I want to do nothing in the case that the client has closed the connection, but log the error if it is any other error. I have encountered the following problems:

  1. The documentation does not seem to say what the errors that conn.Read() can return.
  2. Connection-closed-by-client seems to be an EOF error. Turns out that it's type is error.errorString. Seriously?

So basically I have to do a string comparison to "EOF" to tell if my error is expected or a genuine error?!? Am I missing something? Because this seems like a huge oversight at the moment...

Upvotes: 2

Views: 1161

Answers (1)

kostix
kostix

Reputation: 55553

Well, no, it's string because it's defined as

import "errors"
...
var EOF = errors.New("EOF")

and what errors.New(string) returns is really a type convertible to string because that type, errorString merely embeds a string you're passing to error.New(string) with the sole purpose of defining the Error() string method on it—to satisfy the error interface.

But you test for this specific error (end of file) like this:

import "io"
...
if err == io.EOF {
...

That is, you're not comparing strings but rather addresses of a well-known variable exported by a certain library module ("io" in this case).

Upvotes: 2

Related Questions