43 lines
941 B
Go
43 lines
941 B
Go
package rpc
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
|
|
"nhooyr.io/websocket"
|
|
)
|
|
|
|
func respondError(ctx context.Context, c *websocket.Conn, id string, code int64, err error, data any) {
|
|
slog.ErrorContext(ctx, "Responding to Websocket Request With Error", "err", err, "id", id, "code", code, "data", data)
|
|
var rData []byte
|
|
if data != nil {
|
|
rData, err = json.Marshal(data)
|
|
if err != nil {
|
|
slog.ErrorContext(ctx, "Error Marshalling Error Data", "err", err)
|
|
return
|
|
}
|
|
} else {
|
|
rData = []byte("\"\"")
|
|
}
|
|
|
|
raw := json.RawMessage(rData)
|
|
|
|
resp, err := json.Marshal(Response{
|
|
ID: id,
|
|
Error: &Error{
|
|
Code: code,
|
|
Message: err.Error(),
|
|
Data: &raw,
|
|
},
|
|
})
|
|
if err != nil {
|
|
slog.ErrorContext(ctx, "Error Marshalling Error Response", "err", err)
|
|
return
|
|
}
|
|
err = c.Write(ctx, websocket.MessageText, resp)
|
|
if err != nil {
|
|
slog.ErrorContext(ctx, "Error Sending Error Response", "err", err)
|
|
return
|
|
}
|
|
}
|