Idiomatic error handling for app/e*.go (#9426)

Этот коммит содержится в:
Jesús Espino
2018-09-24 09:22:29 +02:00
коммит произвёл Sudheer
родитель 74c92237c0
Коммит 8898d7aab9
4 изменённых файлов: 113 добавлений и 102 удалений

Просмотреть файл

@@ -18,27 +18,28 @@ func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError {
} }
} }
if esI := a.Elasticsearch; esI != nil { esI := a.Elasticsearch
if err := esI.TestConfig(cfg); err != nil { if esI == nil {
return err
}
} else {
err := model.NewAppError("TestElasticsearch", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented) err := model.NewAppError("TestElasticsearch", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented)
return err return err
} }
if err := esI.TestConfig(cfg); err != nil {
return err
}
return nil return nil
} }
func (a *App) PurgeElasticsearchIndexes() *model.AppError { func (a *App) PurgeElasticsearchIndexes() *model.AppError {
if esI := a.Elasticsearch; esI != nil { esI := a.Elasticsearch
if err := esI.PurgeIndexes(); err != nil { if esI == nil {
return err
}
} else {
err := model.NewAppError("PurgeElasticsearchIndexes", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented) err := model.NewAppError("PurgeElasticsearchIndexes", "ent.elasticsearch.test_config.license.error", nil, "", http.StatusNotImplemented)
return err return err
} }
if err := esI.PurgeIndexes(); err != nil {
return err
}
return nil return nil
} }

Просмотреть файл

@@ -291,6 +291,11 @@ func (a *App) SendInviteEmails(team *model.Team, senderName string, senderUserId
return return
} }
rateLimited, result, err := a.EmailRateLimiter.RateLimit(senderUserId, len(invites)) rateLimited, result, err := a.EmailRateLimiter.RateLimit(senderUserId, len(invites))
if err != nil {
a.Log.Error("Error rate limiting invite email.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(err))
return
}
if rateLimited { if rateLimited {
a.Log.Error("Invite emails rate limited.", a.Log.Error("Invite emails rate limited.",
mlog.String("user_id", senderUserId), mlog.String("user_id", senderUserId),
@@ -298,9 +303,6 @@ func (a *App) SendInviteEmails(team *model.Team, senderName string, senderUserId
mlog.String("retry_after", result.RetryAfter.String()), mlog.String("retry_after", result.RetryAfter.String()),
mlog.Err(err)) mlog.Err(err))
return return
} else if err != nil {
a.Log.Error("Error rate limiting invite email.", mlog.String("user_id", senderUserId), mlog.String("team_id", team.Id), mlog.Err(err))
return
} }
for _, invite := range invites { for _, invite := range invites {

Просмотреть файл

@@ -139,21 +139,26 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu
if inspectedTeamNames[notification.teamName] != "" { if inspectedTeamNames[notification.teamName] != "" {
continue continue
} }
tchan := job.app.Srv.Store.Team().GetByName(notifications[0].teamName)
if result := <-tchan; result.Err != nil { result := <-job.app.Srv.Store.Team().GetByName(notifications[0].teamName)
if result.Err != nil {
mlog.Error(fmt.Sprint("Unable to find Team id for notification", result.Err)) mlog.Error(fmt.Sprint("Unable to find Team id for notification", result.Err))
continue continue
} else if team, ok := result.Data.(*model.Team); ok { }
if team, ok := result.Data.(*model.Team); ok {
inspectedTeamNames[notification.teamName] = team.Id inspectedTeamNames[notification.teamName] = team.Id
} }
// if the user has viewed any channels in this team since the notification was queued, delete // if the user has viewed any channels in this team since the notification was queued, delete
// all queued notifications // all queued notifications
mchan := job.app.Srv.Store.Channel().GetMembersForUser(inspectedTeamNames[notification.teamName], userId) result = <-job.app.Srv.Store.Channel().GetMembersForUser(inspectedTeamNames[notification.teamName], userId)
if result := <-mchan; result.Err != nil { if result.Err != nil {
mlog.Error(fmt.Sprint("Unable to find ChannelMembers for user", result.Err)) mlog.Error(fmt.Sprint("Unable to find ChannelMembers for user", result.Err))
continue continue
} else if channelMembers, ok := result.Data.(*model.ChannelMembers); ok { }
if channelMembers, ok := result.Data.(*model.ChannelMembers); ok {
for _, channelMember := range *channelMembers { for _, channelMember := range *channelMembers {
if channelMember.LastViewedAt >= batchStartTime { if channelMember.LastViewedAt >= batchStartTime {
mlog.Debug(fmt.Sprintf("Deleted notifications for user %s", userId), mlog.String("user_id", userId)) mlog.Debug(fmt.Sprintf("Deleted notifications for user %s", userId), mlog.String("user_id", userId))
@@ -194,38 +199,31 @@ func (job *EmailBatchingJob) checkPendingNotifications(now time.Time, handler fu
} }
func (a *App) sendBatchedEmailNotification(userId string, notifications []*batchedNotification) { func (a *App) sendBatchedEmailNotification(userId string, notifications []*batchedNotification) {
uchan := a.Srv.Store.User().Get(userId) result := <-a.Srv.Store.User().Get(userId)
if result.Err != nil {
var user *model.User
if result := <-uchan; result.Err != nil {
mlog.Warn("Unable to find recipient for batched email notification") mlog.Warn("Unable to find recipient for batched email notification")
return return
} else {
user = result.Data.(*model.User)
} }
user := result.Data.(*model.User)
translateFunc := utils.GetUserTranslations(user.Locale) translateFunc := utils.GetUserTranslations(user.Locale)
displayNameFormat := *a.Config().TeamSettings.TeammateNameDisplay displayNameFormat := *a.Config().TeamSettings.TeammateNameDisplay
var contents string var contents string
for _, notification := range notifications { for _, notification := range notifications {
var sender *model.User result := <-a.Srv.Store.User().Get(notification.post.UserId)
schan := a.Srv.Store.User().Get(notification.post.UserId) if result.Err != nil {
if result := <-schan; result.Err != nil {
mlog.Warn("Unable to find sender of post for batched email notification") mlog.Warn("Unable to find sender of post for batched email notification")
continue continue
} else {
sender = result.Data.(*model.User)
} }
sender := result.Data.(*model.User)
var channel *model.Channel result = <-a.Srv.Store.Channel().Get(notification.post.ChannelId, true)
cchan := a.Srv.Store.Channel().Get(notification.post.ChannelId, true) if result.Err != nil {
if result := <-cchan; result.Err != nil {
mlog.Warn("Unable to find channel of post for batched email notification") mlog.Warn("Unable to find channel of post for batched email notification")
continue continue
} else {
channel = result.Data.(*model.Channel)
} }
channel := result.Data.(*model.Channel)
emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL
if license := a.License(); license != nil && *license.Features.EmailNotificationContents { if license := a.License(); license != nil && *license.Features.EmailNotificationContents {

Просмотреть файл

@@ -49,29 +49,33 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma
return nil, model.NewAppError("createEmoji", "api.emoji.create.duplicate.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("createEmoji", "api.emoji.create.duplicate.app_error", nil, "", http.StatusBadRequest)
} }
if imageData := multiPartImageData.File["image"]; len(imageData) == 0 { imageData := multiPartImageData.File["image"]
if len(imageData) == 0 {
err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": "createEmoji"}, "", http.StatusBadRequest) err := model.NewAppError("Context", "api.context.invalid_body_param.app_error", map[string]interface{}{"Name": "createEmoji"}, "", http.StatusBadRequest)
return nil, err return nil, err
} else if err := a.UploadEmojiImage(emoji.Id, imageData[0]); err != nil {
return nil, err
} }
if result := <-a.Srv.Store.Emoji().Save(emoji); result.Err != nil { if err := a.UploadEmojiImage(emoji.Id, imageData[0]); err != nil {
return nil, result.Err return nil, err
} else {
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EMOJI_ADDED, "", "", "", nil)
message.Add("emoji", emoji.ToJson())
a.Publish(message)
return result.Data.(*model.Emoji), nil
} }
result := <-a.Srv.Store.Emoji().Save(emoji)
if result.Err != nil {
return nil, result.Err
}
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_EMOJI_ADDED, "", "", "", nil)
message.Add("emoji", emoji.ToJson())
a.Publish(message)
return result.Data.(*model.Emoji), nil
} }
func (a *App) GetEmojiList(page, perPage int, sort string) ([]*model.Emoji, *model.AppError) { func (a *App) GetEmojiList(page, perPage int, sort string) ([]*model.Emoji, *model.AppError) {
if result := <-a.Srv.Store.Emoji().GetList(page*perPage, perPage, sort); result.Err != nil { result := <-a.Srv.Store.Emoji().GetList(page*perPage, perPage, sort)
if result.Err != nil {
return nil, result.Err return nil, result.Err
} else {
return result.Data.([]*model.Emoji), nil
} }
return result.Data.([]*model.Emoji), nil
} }
func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError { func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError {
@@ -85,41 +89,52 @@ func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *mode
io.Copy(buf, file) io.Copy(buf, file)
// make sure the file is an image and is within the required dimensions // make sure the file is an image and is within the required dimensions
if config, _, err := image.DecodeConfig(bytes.NewReader(buf.Bytes())); err != nil { config, _, err := image.DecodeConfig(bytes.NewReader(buf.Bytes()))
if err != nil {
return model.NewAppError("uploadEmojiImage", "api.emoji.upload.image.app_error", nil, "", http.StatusBadRequest) return model.NewAppError("uploadEmojiImage", "api.emoji.upload.image.app_error", nil, "", http.StatusBadRequest)
} else if config.Width > MaxEmojiOriginalWidth || config.Height > MaxEmojiOriginalHeight { }
if config.Width > MaxEmojiOriginalWidth || config.Height > MaxEmojiOriginalHeight {
return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.too_large.app_error", map[string]interface{}{ return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.too_large.app_error", map[string]interface{}{
"MaxWidth": MaxEmojiOriginalWidth, "MaxWidth": MaxEmojiOriginalWidth,
"MaxHeight": MaxEmojiOriginalHeight, "MaxHeight": MaxEmojiOriginalHeight,
}, "", http.StatusBadRequest) }, "", http.StatusBadRequest)
} else if config.Width > MaxEmojiWidth || config.Height > MaxEmojiHeight { }
if config.Width > MaxEmojiWidth || config.Height > MaxEmojiHeight {
data := buf.Bytes() data := buf.Bytes()
newbuf := bytes.NewBuffer(nil) newbuf := bytes.NewBuffer(nil)
if info, err := model.GetInfoForBytes(imageData.Filename, data); err != nil { info, err := model.GetInfoForBytes(imageData.Filename, data)
if err != nil {
return err return err
} else if info.MimeType == "image/gif" { }
if gif_data, err := gif.DecodeAll(bytes.NewReader(data)); err != nil {
if info.MimeType == "image/gif" {
gif_data, err := gif.DecodeAll(bytes.NewReader(data))
if err != nil {
return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.gif_decode_error", nil, "", http.StatusBadRequest) return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.gif_decode_error", nil, "", http.StatusBadRequest)
} else { }
resized_gif := resizeEmojiGif(gif_data)
if err := gif.EncodeAll(newbuf, resized_gif); err != nil { resized_gif := resizeEmojiGif(gif_data)
return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.gif_encode_error", nil, "", http.StatusBadRequest) if err := gif.EncodeAll(newbuf, resized_gif); err != nil {
} return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.gif_encode_error", nil, "", http.StatusBadRequest)
if _, err := a.WriteFile(newbuf, getEmojiImagePath(id)); err != nil { }
return err
} if _, err := a.WriteFile(newbuf, getEmojiImagePath(id)); err != nil {
return err
} }
} else { } else {
if img, _, err := image.Decode(bytes.NewReader(data)); err != nil { img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.decode_error", nil, "", http.StatusBadRequest) return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.decode_error", nil, "", http.StatusBadRequest)
} else { }
resized_image := resizeEmoji(img, config.Width, config.Height)
if err := png.Encode(newbuf, resized_image); err != nil { resized_image := resizeEmoji(img, config.Width, config.Height)
return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.encode_error", nil, "", http.StatusBadRequest) if err := png.Encode(newbuf, resized_image); err != nil {
} return model.NewAppError("uploadEmojiImage", "api.emoji.upload.large_image.encode_error", nil, "", http.StatusBadRequest)
if _, err := a.WriteFile(newbuf, getEmojiImagePath(id)); err != nil { }
return err if _, err := a.WriteFile(newbuf, getEmojiImagePath(id)); err != nil {
} return err
} }
} }
} }
@@ -147,11 +162,11 @@ func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) {
return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
} }
if result := <-a.Srv.Store.Emoji().Get(emojiId, false); result.Err != nil { result := <-a.Srv.Store.Emoji().Get(emojiId, false)
if result.Err != nil {
return nil, result.Err return nil, result.Err
} else {
return result.Data.(*model.Emoji), nil
} }
return result.Data.(*model.Emoji), nil
} }
func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) { func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) {
@@ -163,32 +178,30 @@ func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) {
return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusNotImplemented)
} }
if result := <-a.Srv.Store.Emoji().GetByName(emojiName); result.Err != nil { result := <-a.Srv.Store.Emoji().GetByName(emojiName)
if result.Err != nil {
return nil, result.Err return nil, result.Err
} else {
return result.Data.(*model.Emoji), nil
} }
return result.Data.(*model.Emoji), nil
} }
func (a *App) GetEmojiImage(emojiId string) (imageByte []byte, imageType string, err *model.AppError) { func (a *App) GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) {
if result := <-a.Srv.Store.Emoji().Get(emojiId, true); result.Err != nil { result := <-a.Srv.Store.Emoji().Get(emojiId, true)
if result.Err != nil {
return nil, "", result.Err return nil, "", result.Err
} else {
var img []byte
if data, err := a.ReadFile(getEmojiImagePath(emojiId)); err != nil {
return nil, "", model.NewAppError("getEmojiImage", "api.emoji.get_image.read.app_error", nil, err.Error(), http.StatusNotFound)
} else {
img = data
}
_, imageType, err := image.DecodeConfig(bytes.NewReader(img))
if err != nil {
return nil, "", model.NewAppError("getEmojiImage", "api.emoji.get_image.decode.app_error", nil, err.Error(), http.StatusInternalServerError)
}
return img, imageType, nil
} }
img, appErr := a.ReadFile(getEmojiImagePath(emojiId))
if appErr != nil {
return nil, "", model.NewAppError("getEmojiImage", "api.emoji.get_image.read.app_error", nil, appErr.Error(), http.StatusNotFound)
}
_, imageType, err := image.DecodeConfig(bytes.NewReader(img))
if err != nil {
return nil, "", model.NewAppError("getEmojiImage", "api.emoji.get_image.decode.app_error", nil, err.Error(), http.StatusInternalServerError)
}
return img, imageType, nil
} }
func (a *App) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError) { func (a *App) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError) {
@@ -196,11 +209,11 @@ func (a *App) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emo
return nil, model.NewAppError("SearchEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("SearchEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusNotImplemented)
} }
if result := <-a.Srv.Store.Emoji().Search(name, prefixOnly, limit); result.Err != nil { result := <-a.Srv.Store.Emoji().Search(name, prefixOnly, limit)
if result.Err != nil {
return nil, result.Err return nil, result.Err
} else {
return result.Data.([]*model.Emoji), nil
} }
return result.Data.([]*model.Emoji), nil
} }
func resizeEmojiGif(gifImg *gif.GIF) *gif.GIF { func resizeEmojiGif(gifImg *gif.GIF) *gif.GIF {
@@ -231,13 +244,10 @@ func resizeEmoji(img image.Image, width int, height int) image.Image {
emojiWidth := float64(width) emojiWidth := float64(width)
emojiHeight := float64(height) emojiHeight := float64(height)
var emoji image.Image
if emojiHeight <= MaxEmojiHeight && emojiWidth <= MaxEmojiWidth { if emojiHeight <= MaxEmojiHeight && emojiWidth <= MaxEmojiWidth {
emoji = img return img
} else {
emoji = imaging.Fit(img, MaxEmojiWidth, MaxEmojiHeight, imaging.Lanczos)
} }
return emoji return imaging.Fit(img, MaxEmojiWidth, MaxEmojiHeight, imaging.Lanczos)
} }
func imageToPaletted(img image.Image) *image.Paletted { func imageToPaletted(img image.Image) *image.Paletted {