Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Error Handling #8

Merged
merged 6 commits into from
Jan 13, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,4 @@ export [email protected]
export EMAIL_USER=””
export EMAIL_PASSWORD=””
```
You can access the MailHog UI at `localhost:8025`
57 changes: 37 additions & 20 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package cmd
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"log"
"math/rand"
"os"
"path/filepath"
Expand All @@ -15,7 +15,7 @@ import (
"gopkg.in/gomail.v2"
)

var version string = "0.0.1"
var version string = "0.1.0"

type Data struct {
Name string `json:"name"`
Expand Down Expand Up @@ -66,13 +66,13 @@ func sendEmail(to, subject, body string) error {

port, err := strconv.Atoi(strPort)
if err != nil {
return err
return fmt.Errorf("error reading email server port %w", err)
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved
}

d := gomail.NewDialer(host, port, user, password)
s, err := d.Dial()
if err != nil {
return err
return fmt.Errorf("error dialing email server %w", err)
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved
}

m := gomail.NewMessage()
Expand All @@ -84,36 +84,42 @@ func sendEmail(to, subject, body string) error {
return gomail.Send(s, m)
}

func sendEmails(matches []MatchPair) {
func sendEmails(matches []MatchPair) ([]string, error) {
// TODO: add retry logic for failed emails (maybe use a queue)
// instead of sending each email individually,
// generate all the emails and send them in bulk to avoid individual errors
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved
emailIssues := []string{}
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved
subject := "Your Secret Santa Match!"

templateFile := "./templates/email_template.html"
tmpl, err := template.ParseFiles(templateFile)
if err != nil {
log.Fatalf("Error parsing email template: %v", err)
return emailIssues, fmt.Errorf("failed to parse email template: %w", err)
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved
}

for _, match := range matches {
var emailBodyBuffer = &strings.Builder{}
err := tmpl.Execute(emailBodyBuffer, match)
if err != nil {
log.Printf("Error executing template for %s: %v", match.From.Email, err)
continue
emailIssues = append(emailIssues, fmt.Sprintf("failed to execute template for %s: %v", match.From.Email, err))
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved

}
emailBody := emailBodyBuffer.String()

if err := sendEmail(match.From.Email, subject, emailBody); err != nil {
log.Printf("Error sending email to %s: %v", match.From.Email, err)
emailIssues = append(emailIssues, fmt.Sprintf("failed to send email to %s: %v", match.From.Email, err))
}
}
return emailIssues, nil
}

var rootCmd = &cobra.Command{
Use: "run [path]",
Short: "A cli tool that generates secret santa matches and notifies the participants by email",
ArgAliases: []string{"path"},
Version: version,
Run: func(cmd *cobra.Command, args []string) {
Use: "run [path]",
Short: "A cli tool that generates secret santa matches and notifies the participants by email",
ArgAliases: []string{"path"},
Version: version,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
var filePath string
if len(args) == 0 {
filePath = "data.json"
Expand All @@ -125,31 +131,41 @@ var rootCmd = &cobra.Command{
}

if !checkFileExists(filePath) {
log.Fatal("File ", filePath, " does not exist")
return fmt.Errorf("file %s does not exist", filePath)
kkoutsilis marked this conversation as resolved.
Show resolved Hide resolved
}

if !checkIsJson(filePath) {
log.Fatal("File ", filePath, " is not a json file")
return fmt.Errorf("file %s is not a json file", filePath)
}

file, err := os.ReadFile(filePath)
if err != nil {
log.Fatal("Error when opening file: ", err)
return fmt.Errorf("error when opening file: %w", err)
}

var payload []Data
err = json.Unmarshal(file, &payload)
if err != nil {
log.Fatal("Error reading file content: ", err)
return fmt.Errorf("error reading file content: %w", err)
}

if len(payload) == 0 {
log.Fatal("File is empty")
return errors.New("file is empty")
}

matches := generateSecretSantaMatches(payload)
emailIssues, err := sendEmails(matches)
if err != nil {
return fmt.Errorf("error sending emails: %w", err)
}
if len(emailIssues) > 0 {
for _, issue := range emailIssues {
fmt.Println(issue)
}
fmt.Println("Some emails failed to send, please check the logs for more details")
}

sendEmails(matches)
return nil
},
}

Expand All @@ -158,4 +174,5 @@ func Execute() {
if err != nil {
os.Exit(1)
}
os.Exit(0)
}
4 changes: 2 additions & 2 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestGenerateSecretSantaMachesReturnsAppropriateLenghtOfMatchPairs(t *testin
var payload []Data
payload = append(payload, Data{Name: "A", Email: "[email protected]"})
payload = append(payload, Data{Name: "B", Email: "[email protected]"})
payload = append(payload, Data{Name: "C", Email: "testb@test.org"})
payload = append(payload, Data{Name: "C", Email: "testc@test.org"})

matches := generateSecretSantaMatches(payload)

Expand All @@ -47,7 +47,7 @@ func TestCircularMatchingAlgorithmReturnsExpectedMatchPairs(t *testing.T) {
var payload []Data
payload = append(payload, Data{Name: "A", Email: "[email protected]"})
payload = append(payload, Data{Name: "B", Email: "[email protected]"})
payload = append(payload, Data{Name: "C", Email: "testb@test.org"})
payload = append(payload, Data{Name: "C", Email: "testc@test.org"})

var expected []MatchPair

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
)