From 19ca25eb5b7ec17d4e7f57b6024c0dcd646ea689 Mon Sep 17 00:00:00 2001 From: Reinaldy Rafli Date: Sat, 17 Jul 2021 17:34:02 +0700 Subject: [PATCH] fix: handle empty data set --- api/app/v1/core/jokes.go | 7 ++++++- api/app/v1/models/sql.go | 1 + api/app/v1/platform/database/create.go | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/api/app/v1/core/jokes.go b/api/app/v1/core/jokes.go index 1def352..bea84a9 100644 --- a/api/app/v1/core/jokes.go +++ b/api/app/v1/core/jokes.go @@ -45,7 +45,12 @@ func GetRandomJokeFromCache(memory *cache.Cache) (string, error) { return "", nil } - random := rand.Intn(len(data)) + dataLength := len(data) + if dataLength == 0 { + return "", models.ErrEmpty + } + + random := rand.Intn(dataLength) joke := data[random].Link return joke, nil diff --git a/api/app/v1/models/sql.go b/api/app/v1/models/sql.go index 1eb72c5..6938ef1 100644 --- a/api/app/v1/models/sql.go +++ b/api/app/v1/models/sql.go @@ -7,3 +7,4 @@ var ErrConnDone = errors.New("connection is already closed") var ErrTxDone = errors.New("transaction has already been committed or rolled back") var ErrNotFound = errors.New("record not found") +var ErrEmpty = errors.New("record is empty") diff --git a/api/app/v1/platform/database/create.go b/api/app/v1/platform/database/create.go index 9c3e464..457a85d 100644 --- a/api/app/v1/platform/database/create.go +++ b/api/app/v1/platform/database/create.go @@ -7,7 +7,7 @@ import ( "github.com/aldy505/bob" ) -// Set up the table connection, create table if not exists +// Setup the table connection, create table if not exists func Setup() error { db := New()