Skip to content

Commit 6c4aa93

Browse files
committed
fix error handling
1 parent 51070ef commit 6c4aa93

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

server.go

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,10 @@ func (s *Server) handle(conn *websocket.Conn) {
150150

151151
client, err := s.authn(conn)
152152
if err != nil {
153-
s.logger.Errorf("failed to authenticate client: %+v", err)
153+
var authnErr *authnError
154+
if !errors.As(err, &authnErr) {
155+
s.logger.Warnf("failed to authenticate: %+v", err)
156+
}
154157
return
155158
}
156159
s.mu.Lock()
@@ -277,9 +280,20 @@ func (s *Server) unregister(client *clientProxy) {
277280
s.logger.Infof("client unregistered (room: %s, client: %s)", client.roomID, client.clientID)
278281
}
279282

283+
type authnError struct {
284+
Reason string
285+
}
286+
287+
func (e *authnError) Error() string {
288+
return fmt.Sprintf("unauthenticated (reason: %s)", e.Reason)
289+
}
290+
280291
func (s *Server) authn(conn *websocket.Conn) (*clientProxy, error) {
281292
regMsg, err := s.readRegisterMessage(conn)
282293
if err != nil {
294+
if isClosedError(err) {
295+
return nil, &authnError{Reason: "ConnectionClosed"}
296+
}
283297
return nil, fmt.Errorf("failed to read register message: %w", err)
284298
}
285299
authn := s.opts.authn
@@ -302,7 +316,7 @@ func (s *Server) authn(conn *websocket.Conn) (*clientProxy, error) {
302316
Type: MessageTypeReject,
303317
Reason: "InternalServerError",
304318
})
305-
return nil, fmt.Errorf("failed to authenticate: %w", err)
319+
return nil, &authnError{Reason: fmt.Errorf("failed to call authenticator: %w", err).Error()}
306320
}
307321
if !authnResponse.Allowed {
308322
// Although Ayame returns an InternalServerError, Ayu respects the Reason of the Authenticator.
@@ -312,7 +326,7 @@ func (s *Server) authn(conn *websocket.Conn) (*clientProxy, error) {
312326
Type: MessageTypeReject,
313327
Reason: authnResponse.Reason,
314328
})
315-
return nil, fmt.Errorf("unauthenticated (reason: %s)", authnResponse.Reason)
329+
return nil, &authnError{Reason: authnResponse.Reason}
316330
}
317331
s.logger.Infof("authenticated (room: %s, client: %s)", req.RoomID, req.ClientID)
318332
return &clientProxy{
@@ -494,8 +508,10 @@ func (s *Server) forwardBuffered(sender *clientProxy) {
494508

495509
func (s *Server) forwardFromRoom(receiver *clientProxy, payload string) {
496510
if err := s.writeText(receiver.conn, payload); err != nil {
497-
s.logger.Errorf("failed to forward message from room (room: %s, client: %s): %+v",
498-
receiver.roomID, receiver.clientID, err)
511+
if !isClosedError(err) {
512+
s.logger.Errorf("failed to forward message from room (room: %s, client: %s): %+v",
513+
receiver.roomID, receiver.clientID, err)
514+
}
499515
}
500516
}
501517

0 commit comments

Comments
 (0)