[PD1] Error handling project-wide

This commit is contained in:
Afonso Franco 2024-04-28 22:02:13 +01:00
parent f5b3726673
commit b918211736
Signed by: afonso
SSH key fingerprint: SHA256:aiLbdlPwXKJS5wMnghdtod0SPy8imZjlVvCyUX9DJNk
13 changed files with 364 additions and 245 deletions

View file

@ -2,7 +2,6 @@ package networking
import (
"crypto/tls"
"log"
)
@ -14,11 +13,11 @@ type Client[T any] struct {
Connection Connection[T]
}
func NewClient[T any](clientTLSConfigProvider ClientTLSConfigProvider) Client[T] {
func NewClient[T any](clientTLSConfigProvider ClientTLSConfigProvider) (Client[T],error) {
dialConn, err := tls.Dial("tcp", "localhost:8080", clientTLSConfigProvider.GetClientTLSConfig())
if err != nil {
log.Panicln("Server connection error:\n",err)
return Client[T]{},err
}
conn := NewConnection[T](dialConn)
return Client[T]{Connection: conn}
return Client[T]{Connection: conn},nil
}

View file

@ -22,33 +22,27 @@ func NewConnection[T any](netConn *tls.Conn) Connection[T] {
}
}
func (c Connection[T]) Send(obj T) bool {
func (c Connection[T]) Send(obj T) error {
if err := c.encoder.Encode(&obj); err!=nil {
if err == io.EOF {
log.Println("Connection closed by peer")
//Return false as connection not active
return false
} else {
log.Panic(err)
}
}
return err
}
//Return true as connection active
return true
return nil
}
func (c Connection[T]) Receive() (*T, bool) {
func (c Connection[T]) Receive() (*T, error) {
var obj T
if err := c.decoder.Decode(&obj); err != nil {
if err == io.EOF {
log.Println("Connection closed by peer")
//Return false as connection not active
return nil,false
} else {
log.Panic(err)
}
}
}
return nil,err
}
//Return true as connection active
return &obj, true
return &obj, nil
}
func (c Connection[T]) GetPeerCertificate() *x509.Certificate {

View file

@ -2,7 +2,6 @@ package networking
import (
"crypto/tls"
"fmt"
"log"
"net"
)
@ -16,16 +15,16 @@ type Server[T any] struct {
C chan Connection[T]
}
func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider, port int) Server[T] {
func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider) (Server[T], error) {
listener, err := tls.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port), serverTLSConfigProvider.GetServerTLSConfig())
listener, err := tls.Listen("tcp", "127.0.0.1:8080", serverTLSConfigProvider.GetServerTLSConfig())
if err != nil {
log.Fatalln("Server could not bind to address")
return Server[T]{}, err
}
return Server[T]{
listener: listener,
C: make(chan Connection[T]),
}
}, nil
}
func (s *Server[T]) ListenLoop() {
@ -39,7 +38,9 @@ func (s *Server[T]) ListenLoop() {
if !ok {
log.Fatalln("Connection is not a TLS connection")
}
tlsConn.Handshake()
if err := tlsConn.Handshake(); err != nil {
log.Fatalln(err)
}
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) == 0 {