Skip to content

Commit

Permalink
export json : catch errors inside the function
Browse files Browse the repository at this point in the history
  • Loading branch information
letterbeezps committed Jun 21, 2023
1 parent 2bb9d36 commit fe14b77
Showing 1 changed file with 27 additions and 15 deletions.
42 changes: 27 additions & 15 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package clover
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"os"

d "github.com/ostafen/clover/v2/document"
Expand All @@ -19,38 +21,48 @@ func (db *DB) ExportCollection(collectionName string, exportPath string) error {
return ErrCollectionNotExist
}
q := query.NewQuery(collectionName)
collectionCount, err := db.Count(q)
if err != nil {
return err
}

f, err := os.Create(exportPath)
if err != nil {
return err
}
defer f.Close()
if _, err = f.WriteString("["); err != nil {
if _, err := f.WriteString("["); err != nil {
return err
}

n := 0
err = db.ForEach(q, func(doc *d.Document) bool {
n++
var internalErr error
isFirst := true
forEachError := db.ForEach(q, func(doc *d.Document) bool {
jsonByte, err := json.Marshal(doc.AsMap())
if err != nil {
internalErr = err
return false
}
jsonString := string(jsonByte)
if n != collectionCount {
jsonString += ","
if isFirst {
isFirst = false
} else {
jsonString = "," + jsonString
}
if _, err := f.WriteString(jsonString); err != nil {
internalErr = err
return false
}
_, err = f.WriteString(jsonString)
return err == nil
return true
})
if err != nil {
return err
exportErrorLog := ""
if forEachError != nil {
exportErrorLog += fmt.Sprintf("Export JSON file failed, Error from ForEach [%s]", forEachError.Error())
}
if internalErr != nil {
exportErrorLog += fmt.Sprintf(", Error from internal [%s]", internalErr.Error())
}
if _, err = f.WriteString("]"); err != nil {
if exportErrorLog != "" {
return errors.New(exportErrorLog)
}

if _, err := f.WriteString("]"); err != nil {
return err
}
return nil
Expand Down

0 comments on commit fe14b77

Please sign in to comment.