From e12efccb2a39e1df13300fd0dbe6afd061d0cf35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Pilgaard=20Gr=C3=B8ndahl?= Date: Fri, 30 Aug 2024 21:58:22 +0200 Subject: [PATCH] add error handling --- .../Features/PostSearch/PostSearchService.cs | 44 ++++++++++++------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/src/web/Jordnaer/Features/PostSearch/PostSearchService.cs b/src/web/Jordnaer/Features/PostSearch/PostSearchService.cs index 14bf9489..027518a0 100644 --- a/src/web/Jordnaer/Features/PostSearch/PostSearchService.cs +++ b/src/web/Jordnaer/Features/PostSearch/PostSearchService.cs @@ -1,22 +1,26 @@ using Jordnaer.Database; using Jordnaer.Features.Metrics; using Jordnaer.Features.Search; +using Jordnaer.Models; using Jordnaer.Shared; using Microsoft.EntityFrameworkCore; +using OneOf; +using OneOf.Types; namespace Jordnaer.Features.PostSearch; public interface IPostSearchService { - Task GetPostsAsync(PostSearchFilter filter, + Task>> GetPostsAsync(PostSearchFilter filter, CancellationToken cancellationToken = default); } public class PostSearchService( IDbContextFactory contextFactory, - IZipCodeService zipCodeService) : IPostSearchService + IZipCodeService zipCodeService, + ILogger logger) : IPostSearchService { - public async Task GetPostsAsync(PostSearchFilter filter, + public async Task>> GetPostsAsync(PostSearchFilter filter, CancellationToken cancellationToken = default) { JordnaerMetrics.PostSearchesCounter.Add(1, MakeTagList(filter)); @@ -35,19 +39,29 @@ public async Task GetPostsAsync(PostSearchFilter filter, ? 0 : (filter.PageNumber - 1) * filter.PageSize; - var posts = await query.OrderByDescending(x => x.CreatedUtc) - .Skip(postsToSkip) - .Take(filter.PageSize) - .Select(x => x.ToPostDto()) - .ToListAsync(cancellationToken); - - var totalCount = await query.CountAsync(cancellationToken); - - return new PostSearchResult + try { - Posts = posts, - TotalCount = totalCount - }; + var posts = await query.OrderByDescending(x => x.CreatedUtc) + .Skip(postsToSkip) + .Take(filter.PageSize) + .Select(x => x.ToPostDto()) + .ToListAsync(cancellationToken); + + var totalCount = await query.CountAsync(cancellationToken); + + return new PostSearchResult + { + Posts = posts, + TotalCount = totalCount + }; + } + catch (Exception exception) + { + logger.LogError(exception, "Exception occurred during post search. " + + "Query: {Query}", query.ToQueryString()); + } + + return new Error(ErrorMessages.Something_Went_Wrong_Try_Again); } internal async Task> ApplyLocationFilterAsync(