fix issues with error handling

This commit is contained in:
maddalax 2024-10-02 11:06:00 -05:00
parent 33b4b3299e
commit d739ef3758
3 changed files with 10 additions and 19 deletions

View file

@ -26,7 +26,7 @@ func ChatRoom(ctx *h.RequestContext) *h.Page {
js.ConsoleLog("Connected to chat room"),
),
h.HxOnSseClose(
h.HxOnSseError(
js.EvalJs(fmt.Sprintf(`
const reason = e.detail.event.data
if(['invalid room', 'no session', 'invalid user'].includes(reason)) {

View file

@ -31,7 +31,7 @@ func Handle() http.HandlerFunc {
}
ctx := r.Context()
done := make(chan CloseEvent, 1)
done := make(chan bool, 1)
writer := make(WriterChan, 1)
wg := sync.WaitGroup{}
@ -51,18 +51,15 @@ func Handle() http.HandlerFunc {
select {
case <-ctx.Done():
return
case reason := <-done:
fmt.Printf("closing connection: %s\n", reason.Reason)
case <-done:
fmt.Printf("closing connection: \n")
return
case <-ticker.C:
manager.Ping(sessionId)
case message := <-writer:
_, err := fmt.Fprintf(w, message)
if err != nil {
done <- CloseEvent{
Code: -1,
Reason: err.Error(),
}
done <- true
} else {
flusher, ok := w.(http.Flusher)
if ok {

View file

@ -8,7 +8,7 @@ import (
type EventType string
type WriterChan chan string
type DoneChan chan CloseEvent
type DoneChan chan bool
const (
ConnectedEvent EventType = "connected"
@ -101,7 +101,7 @@ func (manager *SocketManager) OnMessage(id string, message map[string]any) {
})
}
func (manager *SocketManager) Add(roomId string, id string, writer chan string, done chan CloseEvent) {
func (manager *SocketManager) Add(roomId string, id string, writer WriterChan, done DoneChan) {
manager.idToRoom.Store(id, roomId)
sockets, ok := manager.sockets.LoadOrCompute(roomId, func() *xsync.MapOf[string, SocketConnection] {
@ -148,11 +148,8 @@ func (manager *SocketManager) CloseWithMessage(id string, message string) {
conn := manager.Get(id)
if conn != nil {
defer manager.OnClose(id)
manager.writeText(*conn, "close", message)
conn.Done <- CloseEvent{
Code: -1,
Reason: message,
}
manager.writeText(*conn, "error", message)
conn.Done <- true
}
}
@ -160,10 +157,7 @@ func (manager *SocketManager) Disconnect(id string) {
conn := manager.Get(id)
if conn != nil {
manager.OnClose(id)
conn.Done <- CloseEvent{
Code: -1,
Reason: "",
}
conn.Done <- true
}
}