Skip to content

Commit

Permalink
New GlobalException Handler
Browse files Browse the repository at this point in the history
  • Loading branch information
novru authored and novru committed May 17, 2024
1 parent dfeb258 commit a610dc4
Show file tree
Hide file tree
Showing 12 changed files with 96 additions and 30 deletions.
4 changes: 4 additions & 0 deletions Api/Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@
<ProjectReference Include="..\Infrastructure\Persistence\Persistence.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="Extensions\" />
</ItemGroup>

</Project>
24 changes: 11 additions & 13 deletions Api/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,36 +45,34 @@ public IActionResult GetAllCourses()
[HttpPut("RateCourse")]
public async Task<IActionResult> RateCourse(RateCourseRequest request)
{
try
{
return Ok(await _userService.RateCourseAsync(request));
}
catch (Exception exception)
{
return BadRequest(exception.Message);
}
return Ok(await _userService.RateCourseAsync(request));
}

[HttpPost("MakeComment")]
public async Task<IActionResult> MakeComment(MakeCommentRequest request)
{
return Ok(await _userService.MakeCommentAsync(request));
}

[HttpGet("GetMyComments")]
public IActionResult GetMyComments(string userId)
{
try
{
return Ok(await _userService.MakeCommentAsync(request));
return Ok(_userService.GetMyComments(userId));
}
catch (Exception exception)
{
return BadRequest(exception.Message);
}
}


[HttpGet("GetMyComments")]
public IActionResult GetMyComments(string userId)
[HttpPut("AddCourseToFavourites")]
public IActionResult AddCourseToFavourites(AddCourseToFavRequest request)
{
try
{
return Ok(_userService.GetMyComments(userId));
return Ok(_userService.AddCourseToFavourites(request));
}
catch (Exception exception)
{
Expand Down
22 changes: 22 additions & 0 deletions Api/GlobalException/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Application.Exceptions;
using Microsoft.AspNetCore.Diagnostics;

namespace Api.GlobalException;

public class GlobalExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
(int statusCode, string errorMessage) = exception switch
{
InvalidRatingException => (StatusCodes.Status406NotAcceptable, "Rating must be between 1 and 5, Please provide correct number"),
UserNotFoundException => (StatusCodes.Status404NotFound, "Cannot find user, check user credentials"),
CourseNotFoundException => (StatusCodes.Status404NotFound, "Cannot find course, check course credentials"),
_ => (500, "Error occured, Try again.")
}; ;

httpContext.Response.StatusCode = statusCode;
await httpContext.Response.WriteAsJsonAsync(errorMessage);
return true;
}
}
4 changes: 4 additions & 0 deletions Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Api.Extensions;
using Api.GlobalException;
using Application.Models.Configurations;
using Microsoft.EntityFrameworkCore;
using Persistence.Context;
Expand All @@ -15,6 +16,7 @@
builder.Services.AddRepositories();
builder.Services.AddAuthenticationAndAuthorization(builder.Configuration);
builder.Services.AddSwagger();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var cosmos = new CosmosConfiguration();
builder.Configuration.GetSection("Cosmos").Bind(cosmos);
builder.Services.Configure<BlobStorageConfiguration>(builder.Configuration.GetSection("BlobStorage"));
Expand All @@ -31,6 +33,8 @@

app.UseHttpsRedirection();

app.UseExceptionHandler("/err");

app.UseAuthorization();

app.MapControllers();
Expand Down
2 changes: 2 additions & 0 deletions Core/Application/Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

<ItemGroup>
<PackageReference Include="Azure.Storage.Blobs" Version="12.20.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Cosmos" Version="8.0.4" />
Expand Down
9 changes: 9 additions & 0 deletions Core/Application/Exceptions/CourseNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Application.Exceptions;

public class CourseNotFoundException : Exception
{
public CourseNotFoundException():base()
{

}
}
7 changes: 2 additions & 5 deletions Core/Application/Exceptions/InvalidRatingException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@

public class InvalidRatingException : Exception
{
public InvalidRatingException(string? message) : base(message)
{
}

public InvalidRatingException(string? message, Exception? innerException) : base(message, innerException)
public InvalidRatingException()
{

}
}
12 changes: 12 additions & 0 deletions Core/Application/Exceptions/UserNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Application.Exceptions;

public class UserNotFoundException : Exception
{
public UserNotFoundException(string? message) : base(message)
{
}

public UserNotFoundException(string? message, Exception? innerException) : base(message, innerException)
{
}
}
8 changes: 8 additions & 0 deletions Core/Application/Models/Requests/AddCourseToFavRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Application.Models.Requests;

public class AddCourseToFavRequest
{
public string CourseId { get; set; }
public string UserId { get; set; }

}
1 change: 0 additions & 1 deletion Core/Application/Services/IHostService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,5 @@ public interface IHostService
Task<bool> RemoveCourseAsync(string courseId);

Task<bool> BanUser(string userId);

Task<bool> ConfirmAndRemoveAccount(RemoveMyAccountRequest request);
}
1 change: 1 addition & 0 deletions Core/Application/Services/IUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ public interface IUserService
IEnumerable<BookInfo> GetAllBooks();
Task<bool> RateCourseAsync(RateCourseRequest request);
Task<bool> MakeCommentAsync(MakeCommentRequest request);
Task<bool> AddCourseToFavourites(AddCourseToFavRequest request);
}
32 changes: 21 additions & 11 deletions Infrastructure/Infrastructure/Services/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public async Task<bool> MakeCommentAsync(MakeCommentRequest request)
var course = await _unitOfWork.ReadCourseRepository.GetAsync(request.CourseId);

if (user == null || course == null)
return false;
throw new UserNotFoundException("Cannot find user");

var newComment = CreateNewComment(request);

Expand All @@ -111,23 +111,34 @@ private async Task<bool> AddNewComment(Comment newComment)
public async Task<bool> RateCourseAsync(RateCourseRequest request)
{
if (request.Rate > 5 || request.Rate < 1)
{
throw new InvalidRatingException("The rating value must be between 1 and 5. Please provide a valid rating.");
}

var course = await _unitOfWork.ReadCourseRepository.GetAsync(request.CourseId);
throw new InvalidRatingException();

if (course is null)
{
throw new ArgumentNullException(nameof(course));
}
var course = await _unitOfWork.ReadCourseRepository.GetAsync(request.CourseId)??
throw new CourseNotFoundException();

course.Rating = course.RatingsCount == 0 ? request.Rate : (course.Rating + request.Rate) / course.RatingsCount++;
var result = _unitOfWork.WriteCourseRepository.Update(course);
await _unitOfWork.WriteCourseRepository.SaveChangesAsync();
return result;
}

public async Task<bool> AddCourseToFavourites(AddCourseToFavRequest request)
{
var course = await _unitOfWork.ReadCourseRepository.GetAsync(request.CourseId) ?? throw new NullReferenceException();
course.FavCount++;

var user = await _unitOfWork.ReadUserRepository.GetAsync(request.UserId);
user.FavouritesIds.Add(course.Id);

await _unitOfWork.WriteUserRepository.UpdateAsync(user.Id);
await _unitOfWork.WriteCourseRepository.UpdateAsync(course.Id);

await _unitOfWork.WriteUserRepository.SaveChangesAsync();

return true;
}


// Helper Methods

private Comment CreateNewComment(MakeCommentRequest request)
Expand All @@ -147,5 +158,4 @@ private void UpdateUserAndCourseComments(User user, Course course, Comment newCo
user.CommentIds.Add(newComment.Id);
course.CommentIds.Add(newComment.Id);
}

}

0 comments on commit a610dc4

Please sign in to comment.