Skip to content

Commit

Permalink
migrated some of the if-error statements to this syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
CommanderStorm committed Sep 13, 2023
1 parent 2b31893 commit 431e69a
Show file tree
Hide file tree
Showing 8 changed files with 22 additions and 47 deletions.
6 changes: 2 additions & 4 deletions client/localServer/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,7 @@ func getImageToBytes(path string) []byte {
}

defer func(file *os.File) {
err := file.Close()
if err != nil {
if err := file.Close(); err != nil {
log.WithError(err).Error("could not close file")
}
}(file)
Expand Down Expand Up @@ -291,8 +290,7 @@ func storeImage(path string, i []byte) (string, error) {
log.WithError(errFile).Error("Unable to create the new testfile")
}
defer func(out *os.File) {
err := out.Close()
if err != nil {
if err := out.Close(); err != nil {
log.WithError(err).Error("File was not closed successfully")
}
}(out)
Expand Down
3 changes: 1 addition & 2 deletions client/publicServer/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ func main() {
log.WithError(err).Fatal("did not connect")
}
defer func(conn *grpc.ClientConn) {
err := conn.Close()
if err != nil {
if err := conn.Close(); err != nil {
log.WithError(err).Error("did not close connection")
}
}(conn)
Expand Down
6 changes: 2 additions & 4 deletions server/backend/cafeteriaRatingDBInitializer.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,7 @@ func generateNameTagListFromFile(path string) multiLanguageNameTags {
log.WithError(errjson).Error("Error while reading the file.")
}
defer func(jsonFile *os.File) {
err := jsonFile.Close()
if err != nil {
if err := jsonFile.Close(); err != nil {
log.WithError(err).Error("Error in parsing json.")
}
}(file)
Expand All @@ -224,8 +223,7 @@ func generateRatingTagListFromFile(path string) multiLanguageTags {
log.WithError(errjson).Error("Error while reading or parsing the file.")
}
defer func(jsonFile *os.File) {
err := jsonFile.Close()
if err != nil {
if err := jsonFile.Close(); err != nil {
log.WithError(err).Error("Error in parsing json.")
}
}(file)
Expand Down
22 changes: 7 additions & 15 deletions server/backend/cafeteriaService.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,15 +249,12 @@ func getImageToBytes(path string) []byte {
return make([]byte, 0)
}
file, err := os.Open(path)

if err != nil {
log.WithError(err).Error("while opening image file with path: ", path)
return nil
}

defer func(file *os.File) {
err := file.Close()
if err != nil {
if err := file.Close(); err != nil {
log.WithError(err).Error("Unable to close the file for storing the image.")
}
}(file)
Expand All @@ -267,8 +264,7 @@ func getImageToBytes(path string) []byte {
imageAsBytes := make([]byte, size)

buffer := bufio.NewReader(file)
_, err = buffer.Read(imageAsBytes)
if err != nil {
if _, err = buffer.Read(imageAsBytes); err != nil {
log.WithError(err).Error("while trying to read image as bytes")
return nil
}
Expand Down Expand Up @@ -376,8 +372,7 @@ func (s *CampusServer) NewCafeteriaRating(_ context.Context, input *pb.NewCafete
Image: resPath,
}

err := s.db.Model(&model.CafeteriaRating{}).Create(&rating).Error
if err != nil {
if err := s.db.Model(&model.CafeteriaRating{}).Create(&rating).Error; err != nil {
log.WithError(err).Error("Error occurred while creating the new cafeteria rating.")
return nil, status.Errorf(codes.InvalidArgument, "Error while creating new cafeteria rating. Rating has not been saved.")

Expand All @@ -400,12 +395,11 @@ func imageWrapper(image []byte, path string, id int32) string {
}

// storeImage
// stores an image and returns teh path to this image.
// stores an image and returns the path to this image.
// if needed, a new directory will be created and the path is extended until it is unique
func storeImage(path string, i []byte) (string, error) {
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
if err := os.MkdirAll(path, os.ModePerm); err != nil {
log.WithError(err).WithField("path", path).Error("Directory could not be created successfully")
return "", nil
}
Expand All @@ -430,8 +424,7 @@ func storeImage(path string, i []byte) (string, error) {
return imgPath, errFile
}
defer func(out *os.File) {
err := out.Close()
if err != nil {
if err := out.Close(); err != nil {
log.WithError(err).Error("while closing the file.")
}
}(out)
Expand Down Expand Up @@ -473,8 +466,7 @@ func (s *CampusServer) NewDishRating(_ context.Context, input *pb.NewDishRatingR
Image: resPath,
}

err := s.db.Model(&model.DishRating{}).Create(&rating).Error
if err != nil {
if err := s.db.Model(&model.DishRating{}).Create(&rating).Error; err != nil {
log.WithError(err).Error("while creating a new dish rating.")
return nil, status.Errorf(codes.Internal, "Error while creating the new rating in the database. Rating has not been saved.")
}
Expand Down
9 changes: 2 additions & 7 deletions server/backend/campus_api/campusApi.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,18 @@ func FetchGrades(token string) (*model.IOSGrades, error) {
req.URL.RawQuery = q.Encode()

resp, err := http.DefaultClient.Do(req)

if err != nil {
log.WithError(err).Error("failed to fetch grades")
return nil, ErrWhileFetchingGrades
}

defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
if err := Body.Close(); err != nil {
log.WithError(err).Error("Could not close body")
}
}(resp.Body)

var grades model.IOSGrades
err = xml.NewDecoder(resp.Body).Decode(&grades)

if err != nil {
if err = xml.NewDecoder(resp.Body).Decode(&grades); err != nil {
log.WithError(err).Error("could not unmarshall grades")
return nil, ErrorWhileUnmarshalling
}
Expand Down
13 changes: 5 additions & 8 deletions server/backend/cron/canteenHeadCount.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,17 +189,16 @@ func updateDb(canteen *CanteenApInformation, count uint32, db *gorm.DB) error {
}

if res.RowsAffected == 0 {
err := db.Create(&entry).Error
if err != nil {
if err := db.Create(&entry).Error; err != nil {
fields := log.Fields{
"CanteenId": entry.CanteenId,
"Count": entry.Count,
"MaxCount": entry.MaxCount,
"Percent": entry.Percent,
"Timestamp": entry.Timestamp}
log.WithError(res.Error).WithFields(fields).Error("could not create headcount entry")
return err
}
return err
}
return nil
}
Expand All @@ -216,17 +215,15 @@ func (canteen CanteenApInformation) requestApData() []AccessPoint {
// Ensure we close the body once we leave this function
if resp.Body != nil {
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
if err := Body.Close(); err != nil {
log.WithError(err).Error("Could not close body")
}
}(resp.Body)
}

// Parse as JSON
aps := []AccessPoint{}
err = json.NewDecoder(resp.Body).Decode(&aps)
if err != nil {
var aps []AccessPoint
if err = json.NewDecoder(resp.Body).Decode(&aps); err != nil {
log.WithError(err).Error("Canteen HeadCount parsing output as JSON failed for: ", canteen.CanteenId)
return []AccessPoint{}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,11 @@ func (r *Repository) SendNotification(notification *model.IOSNotificationPayload

resp, err := client.Do(req)
if err != nil {
log.Error(err)
log.WithError(err).Error("Could not send notification")
return nil, ErrCouldNotSendNotification
}

defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
if err := Body.Close(); err != nil {
log.WithError(err).Error("Could not close body")
}
}(resp.Body)
Expand Down
4 changes: 1 addition & 3 deletions server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,7 @@ func errorHandler(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(errorResp.StatusCode)

err = json.NewEncoder(w).Encode(errorResp)

if err != nil {
if err = json.NewEncoder(w).Encode(errorResp); err != nil {
log.WithError(err).Error("Marshal error response failed")
return
}
Expand Down

0 comments on commit 431e69a

Please sign in to comment.