encoding/json panic recovery

This commit is contained in:
Gennadii Kovalev 2017-03-15 15:30:36 +02:00
parent 1f0997054e
commit 1f2f313d47
1 changed files with 14 additions and 6 deletions

20
send.go
View File

@ -3,8 +3,9 @@ package gosocketio
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"time"
"github.com/graarh/golang-socketio/protocol" "github.com/graarh/golang-socketio/protocol"
"log"
"time"
) )
var ( var (
@ -16,6 +17,13 @@ var (
Send message packet to socket Send message packet to socket
*/ */
func send(msg *protocol.Message, c *Channel, args interface{}) error { func send(msg *protocol.Message, c *Channel, args interface{}) error {
//preventing json/encoding "index out of range" panic
defer func() {
if r := recover(); r != nil {
log.Println("socket.io send panic: ", r)
}
}()
if args != nil { if args != nil {
json, err := json.Marshal(&args) json, err := json.Marshal(&args)
if err != nil { if err != nil {
@ -44,8 +52,8 @@ Create packet based on given data and send it
*/ */
func (c *Channel) Emit(method string, args interface{}) error { func (c *Channel) Emit(method string, args interface{}) error {
msg := &protocol.Message{ msg := &protocol.Message{
Type: protocol.MessageTypeEmit, Type: protocol.MessageTypeEmit,
Method: method, Method: method,
} }
return send(msg, c, args) return send(msg, c, args)
@ -56,9 +64,9 @@ Create ack packet based on given data and send it and receive response
*/ */
func (c *Channel) Ack(method string, args interface{}, timeout time.Duration) (string, error) { func (c *Channel) Ack(method string, args interface{}, timeout time.Duration) (string, error) {
msg := &protocol.Message{ msg := &protocol.Message{
Type: protocol.MessageTypeAckRequest, Type: protocol.MessageTypeAckRequest,
AckId: c.ack.getNextId(), AckId: c.ack.getNextId(),
Method: method, Method: method,
} }
waiter := make(chan string) waiter := make(chan string)