Skip to content

Commit

Permalink
Merge pull request #37 from Star-Academy/feature/error-code
Browse files Browse the repository at this point in the history
feat: add error code to result
  • Loading branch information
mobinbr authored Sep 8, 2024
2 parents bb4d055 + a06d4d9 commit 7f1e22c
Show file tree
Hide file tree
Showing 12 changed files with 73 additions and 314 deletions.
9 changes: 9 additions & 0 deletions src/Application/DTOs/ErrorCode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Application.DTOs;

public enum ErrorCode
{
BadRequest = 400,
UnAuthorized = 401,
NotFound = 404,
InternalServerError = 500,
}
12 changes: 7 additions & 5 deletions src/Application/DTOs/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class Result
{
public string Message { get; protected set; } = string.Empty;
public bool Succeed { get; protected set; }

public ErrorCode ErrCode { get; protected set; }
public static Result Ok(string message = "succeed")
{
return new Result
Expand All @@ -14,12 +14,13 @@ public static Result Ok(string message = "succeed")
};
}

public static Result Fail(string message = "failed")
public static Result Fail(ErrorCode errorCode, string message = "failed")
{
return new Result
{
Succeed = false,
Message = message
Message = message,
ErrCode = errorCode
};
}
}
Expand All @@ -37,12 +38,13 @@ public static Result<T> Ok(T value)
};
}

public static Result<T> Fail(string message = "failed")
public static Result<T> Fail(ErrorCode errorCode, string message = "failed")
{
return new Result<T>
{
Succeed = false,
Message = message
Message = message,
ErrCode = errorCode
};
}
}
18 changes: 9 additions & 9 deletions src/Application/Services/DomainService/AccountService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@ public async Task<Result> AddAccountsFromCsvAsync(string filePath, long fileId)
var fileAlreadyExists = await _fileIdRepository.IdExistsAsync(fileId);
if (fileAlreadyExists)
{
return Result.Fail("File-Id already exists");
return Result.Fail(ErrorCode.BadRequest, "File-Id already exists");
}
await _fileIdRepository.AddAsync(new FileId { Id = fileId });
await _accountRepository.CreateBulkAsync(newAccounts);
return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail($"An unexpected error occurred: {ex.Message}");
return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -57,14 +57,14 @@ public async Task<Result<Account>> GetAccountByIdAsync(long accountId)
var account = await _accountRepository.GetByIdAsync(accountId);
if (account == null)
{
return Result<Account>.Fail("Account not found");
return Result<Account>.Fail(ErrorCode.NotFound, "Account not found");
}

return Result<Account>.Ok(account);
}
catch (Exception ex)
{
return Result<Account>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<Account>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -77,7 +77,7 @@ public async Task<Result<List<Account>>> GetAllAccountsAsync()
}
catch (Exception ex)
{
return Result<List<Account>>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<List<Account>>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -87,14 +87,14 @@ public async Task<Result<List<Account>>> GetAccountsByFileIdAsync(long fileId)
{
if (!await _fileIdRepository.IdExistsAsync(fileId))
{
return Result<List<Account>>.Fail("File-Id not found");
return Result<List<Account>>.Fail(ErrorCode.BadRequest, "File-Id not found");
}
var accounts = await _accountRepository.GetByFileIdAsync(fileId);
return Result<List<Account>>.Ok(accounts);
}
catch (Exception ex)
{
return Result<List<Account>>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<List<Account>>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -104,15 +104,15 @@ public async Task<Result> DeleteAccountsByFileIdAsync(long fileId)
{
if (!await _fileIdRepository.IdExistsAsync(fileId))
{
return Result<List<Account>>.Fail("File-Id not found");
return Result<List<Account>>.Fail(ErrorCode.BadRequest, "File-Id not found");
}
await _accountRepository.DeleteByFileIdAsync(fileId);
await _fileIdRepository.DeleteByIdAsync(fileId);
return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail($"An unexpected error occurred: {ex.Message}");
return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}
}
20 changes: 10 additions & 10 deletions src/Application/Services/DomainService/ProfileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ public async Task<Result<EditProfileInfoResponse>> EditProfileInfo(EditProfileIn
{
var user = await _userManagerRepository.FindByIdAsync(infoRequest.UserId);
if (user == null)
return Result<EditProfileInfoResponse>.Fail("User not found!");
return Result<EditProfileInfoResponse>.Fail(ErrorCode.BadRequest, "User not found!");

if (user.UserName != infoRequest.UserName)
{
var existingUser = await _userManagerRepository.FindByNameAsync(infoRequest.UserName);
if (existingUser != null)
return Result<EditProfileInfoResponse>.Fail("Username is already reserved by another user!");
return Result<EditProfileInfoResponse>.Fail(ErrorCode.BadRequest, "Username is already reserved by another user!");
}

user.UserName = infoRequest.UserName;
Expand All @@ -39,13 +39,13 @@ public async Task<Result<EditProfileInfoResponse>> EditProfileInfo(EditProfileIn

var updateResult = await _userManagerRepository.UpdateAsync(user);
if (!updateResult.Succeeded)
return Result<EditProfileInfoResponse>.Fail(updateResult.Errors.FirstMessage());
return Result<EditProfileInfoResponse>.Fail(ErrorCode.BadRequest, updateResult.Errors.FirstMessage());

return Result<EditProfileInfoResponse>.Ok(user.ToEditProfileInfoResponse());
}
catch (Exception ex)
{
return Result<EditProfileInfoResponse>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<EditProfileInfoResponse>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -56,15 +56,15 @@ public async Task<Result<GetProfileInfoResponse>> GetProfileInfo(GetProfileInfoR
var user = await _userManagerRepository.FindByIdAsync(getProfileInfoRequest.UserId);

if (user == null)
return Result<GetProfileInfoResponse>.Fail("User not found!");
return Result<GetProfileInfoResponse>.Fail(ErrorCode.NotFound, "User not found!");

var role = await _userManagerRepository.GetRoleAsync(user);

return Result<GetProfileInfoResponse>.Ok(user.ToGetProfileInfoResponse(role));
}
catch (Exception ex)
{
return Result<GetProfileInfoResponse>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<GetProfileInfoResponse>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -74,21 +74,21 @@ public async Task<Result> ChangePassword(ChangePasswordRequest request)
{
var user = await _userManagerRepository.FindByIdAsync(request.UserId);
if (user == null)
return Result.Fail("User not found!");
return Result.Fail(ErrorCode.BadRequest, "User not found!");

var isPasswordCorrect = await _userManagerRepository.CheckPasswordAsync(user, request.CurrentPassword);
if (!isPasswordCorrect)
return Result.Fail("Incorrect current password!");
return Result.Fail(ErrorCode.BadRequest, "Incorrect current password!");

var passwordChangeResult = await _userManagerRepository.ChangePasswordAsync(user, request.CurrentPassword, request.NewPassword);
if (!passwordChangeResult.Succeeded)
return Result.Fail(passwordChangeResult.Errors.FirstMessage());
return Result.Fail(ErrorCode.BadRequest, passwordChangeResult.Errors.FirstMessage());

return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail($"An unexpected error occurred: {ex.Message}");
return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}
}
16 changes: 8 additions & 8 deletions src/Application/Services/DomainService/TransactionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task<Result> AddTransactionsFromCsvAsync(string filePath, long file
var fileAlreadyExists = await _fileIdRepository.IdExistsAsync(fileId);
if (!fileAlreadyExists)
{
return Result.Fail("File-Id do not exist");
return Result.Fail(ErrorCode.BadRequest, "File-Id do not exist");
}
await _transactionRepository.CreateBulkAsync(newTransactions);
return Result.Ok(invalidTransactionCsvModels.Count == 0
Expand All @@ -71,7 +71,7 @@ public async Task<Result> AddTransactionsFromCsvAsync(string filePath, long file
}
catch (Exception ex)
{
return Result.Fail($"An error occurred: {ex.Message}");
return Result.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}");
}
}

Expand All @@ -84,7 +84,7 @@ public async Task<Result<List<Transaction>>> GetAllTransactionsAsync()
}
catch (Exception ex)
{
return Result<List<Transaction>>.Fail($"An error occurred: {ex.Message}");
return Result<List<Transaction>>.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}");
}
}

Expand Down Expand Up @@ -129,7 +129,7 @@ public async Task<Result<List<GetTransactionsByAccountIdResponse>>> GetTransacti
}
catch (Exception ex)
{
return Result<List<GetTransactionsByAccountIdResponse>>.Fail($"An error occurred: {ex.Message}");
return Result<List<GetTransactionsByAccountIdResponse>>.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}");
}
}

Expand All @@ -139,14 +139,14 @@ public async Task<Result<List<Transaction>>> GetTransactionsByFileIdAsync(long f
{
if (!await _fileIdRepository.IdExistsAsync(fileId))
{
return Result<List<Transaction>>.Fail("File-Id not found");
return Result<List<Transaction>>.Fail(ErrorCode.BadRequest, "File-Id not found");
}
var transactions = await _transactionRepository.GetByFileIdAsync(fileId);
return Result<List<Transaction>>.Ok(transactions);
}
catch (Exception ex)
{
return Result<List<Transaction>>.Fail($"An error occurred: {ex.Message}");
return Result<List<Transaction>>.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}");
}
}

Expand All @@ -156,14 +156,14 @@ public async Task<Result> DeleteTransactionsByFileIdAsync(long fileId)
{
if (!await _fileIdRepository.IdExistsAsync(fileId))
{
return Result.Fail("File-Id not found");
return Result.Fail(ErrorCode.BadRequest, "File-Id not found");
}
await _transactionRepository.DeleteByFileIdAsync(fileId);
return Result.Ok();
}
catch (Exception ex)
{
return Result.Fail($"An error occurred: {ex.Message}");
return Result.Fail(ErrorCode.InternalServerError, $"An error occurred: {ex.Message}");
}
}
}
26 changes: 13 additions & 13 deletions src/Application/Services/DomainService/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,28 @@ public async Task<Result<CreateUserResponse>> SignUp(CreateUserRequest createUse
{
if (!await _roleManagerRepository.RoleExistsAsync(createUserRequest.Role))
{
return Result<CreateUserResponse>.Fail("Role does not exist.");
return Result<CreateUserResponse>.Fail(ErrorCode.BadRequest, "Role does not exist.");
}

var appUser = createUserRequest.ToAppUser();

var appUserResult = await _userManagerRepository.CreateAsync(appUser, createUserRequest.Password);
if (!appUserResult.Succeeded)
{
return Result<CreateUserResponse>.Fail(appUserResult.Errors.FirstMessage());
return Result<CreateUserResponse>.Fail(ErrorCode.BadRequest, appUserResult.Errors.FirstMessage());
}

var roleResult = await _userManagerRepository.SetRoleAsync(appUser, createUserRequest.Role);
if (!roleResult.Succeeded)
{
return Result<CreateUserResponse>.Fail(roleResult.Errors.FirstMessage());
return Result<CreateUserResponse>.Fail(ErrorCode.BadRequest, roleResult.Errors.FirstMessage());
}

return Result<CreateUserResponse>.Ok(appUser.ToCreateUserResponse(createUserRequest.Role));
}
catch (Exception ex)
{
return Result<CreateUserResponse>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<CreateUserResponse>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -72,14 +72,14 @@ public async Task<Result<LoginUserResponse>> Login(LoginUserRequest loginUserReq
}
else
{
return Result<LoginUserResponse>.Fail("You should enter email or username!");
return Result<LoginUserResponse>.Fail(ErrorCode.UnAuthorized, "You should enter email or username!");
}

if (appUser is null) return Result<LoginUserResponse>.Fail("Invalid username/email!");
if (appUser is null) return Result<LoginUserResponse>.Fail(ErrorCode.UnAuthorized, "Invalid username/email!");

var succeed = await _userManagerRepository.CheckPasswordAsync(appUser, loginUserRequest.Password);

if (!succeed) return Result<LoginUserResponse>.Fail("Username/Email not found and/or password incorrect");
if (!succeed) return Result<LoginUserResponse>.Fail(ErrorCode.UnAuthorized, "Username/Email not found and/or password incorrect");

var role = await _userManagerRepository.GetRoleAsync(appUser);
var token = _tokenService.GenerateToken(appUser, role);
Expand All @@ -88,7 +88,7 @@ public async Task<Result<LoginUserResponse>> Login(LoginUserRequest loginUserReq
}
catch (Exception ex)
{
return Result<LoginUserResponse>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<LoginUserResponse>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -98,19 +98,19 @@ public async Task<Result> ChangeRole(ChangeRoleRequest request)
{
if (!await _roleManagerRepository.RoleExistsAsync(request.Role))
{
return Result.Fail("role does not exist");
return Result.Fail(ErrorCode.BadRequest, "role does not exist");
}
AppUser? appUser = await _userManagerRepository.FindByNameAsync(request.UserName);

if (appUser is null) return Result<LoginUserResponse>.Fail("Invalid username");
if (appUser is null) return Result<LoginUserResponse>.Fail(ErrorCode.BadRequest, "Invalid username");

var result = await _userManagerRepository.ChangeRoleAsync(appUser, request.Role);

return result.Succeeded ? Result.Ok() : Result.Fail(result.Errors.FirstMessage());
return result.Succeeded ? Result.Ok() : Result.Fail(ErrorCode.BadRequest, result.Errors.FirstMessage());
}
catch (Exception ex)
{
return Result.Fail($"An unexpected error occurred: {ex.Message}");
return Result.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}

Expand All @@ -132,7 +132,7 @@ public async Task<Result<List<GetUserResponse>>> GetAllUsersAsync()
}
catch (Exception ex)
{
return Result<List<GetUserResponse>>.Fail($"An unexpected error occurred: {ex.Message}");
return Result<List<GetUserResponse>>.Fail(ErrorCode.InternalServerError, $"An unexpected error occurred: {ex.Message}");
}
}
}
Loading

0 comments on commit 7f1e22c

Please sign in to comment.