Skip to content

Commit

Permalink
chore: Remove unnecessary error logging in PortfolioServiceImpl
Browse files Browse the repository at this point in the history
  • Loading branch information
djangbahevans committed Aug 9, 2024
1 parent 153ea13 commit 931704c
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,11 @@ public ResponseEntity<PaginatedResponseDto<UserResponseDto>> getAllUsers(UserFil
public ResponseEntity<UserResponseDto> updateUser(@PathVariable("id") Long userId,
@Valid @RequestBody UpdateUserDto updatedUser) throws ResourceNotFoundException, IllegalArgumentException {
var auth = SecurityContextHolder.getContext().getAuthentication();
var principal = (User) auth.getPrincipal();

var principal = auth.getPrincipal();
if (principal instanceof User) {
var user = (User) principal;
if (user.getAccountType().equals(AccountType.USER)
&& updatedUser.getAccountType().equals(AccountType.ADMIN)) {
throw new IllegalArgumentException("You are not authorized to update user to admin");
}
} else {
// TODO: Throw a custom exception, if the principal is not an instance of User
throw new IllegalArgumentException("You are not authorized to update user");
if (principal.getAccountType().equals(AccountType.USER)
&& updatedUser.getAccountType().equals(AccountType.ADMIN)) {
throw new IllegalArgumentException("You are not authorized to update user to admin");
}

User userDto = userService.updateUser(userId, updatedUser);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ private void deletePortfolio(PortfolioEventDto portfolio) {
try {
natsService.publish(Event.USER_DELETED, userMapper.toUserEventDto(u));
} catch (JsonProcessingException e) {
System.err.println("Error deleting user");
e.printStackTrace();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
Expand Down Expand Up @@ -40,11 +38,11 @@ public class UserServiceImpl implements UserService {
private NatsService natsService;
private UserMapper userMapper;

private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
private static final String USER_NOT_FOUND = "User does not exist";

public User getUserById(Long userId) throws ResourceNotFoundException {
return userRepository.findById(userId).orElseThrow(
() -> new ResourceNotFoundException("User does not exist"));
() -> new ResourceNotFoundException(USER_NOT_FOUND));
}

@Override
Expand Down Expand Up @@ -108,7 +106,7 @@ public Page<User> getUsers(UserFilterRequestDto filterRequestDto) {
@Override
public User updateUser(Long userId, UpdateUserDto updatedUser) throws ResourceNotFoundException {
User existingUser = userRepository.findById(userId).orElseThrow(
() -> new ResourceNotFoundException("User does not exist"));
() -> new ResourceNotFoundException(USER_NOT_FOUND));

existingUser.setName(updatedUser.getName());
existingUser.setEmail(updatedUser.getEmail());
Expand All @@ -130,7 +128,7 @@ public User updateUser(Long userId, UpdateUserDto updatedUser) throws ResourceNo
@Override
public void deleteUser(Long userId) throws RuntimeException, ResourceNotFoundException {
User user = userRepository.findById(userId).orElseThrow(
() -> new ResourceNotFoundException("User does not exist"));
() -> new ResourceNotFoundException(USER_NOT_FOUND));
List<Portfolio> portfolios = portfolioRepository.findByUserId(userId);

if (portfolios.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,42 +24,42 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ProblemDetail handleSecurityException(Exception exception) {
ProblemDetail errorDetail = null;
var descField = "description";

// TODO send this stack trace to an observability tool
exception.printStackTrace();

if (exception instanceof BadCredentialsException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(401), exception.getMessage());
errorDetail.setProperty("description", "The email or password is incorrect");
errorDetail.setProperty(descField, "The email or password is incorrect");
errorDetail.setTitle("Authentication Error");
return errorDetail;
}

if (exception instanceof AccountStatusException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(403), exception.getMessage());
errorDetail.setProperty("description", "The account is locked");
errorDetail.setProperty(descField, "The account is locked");
errorDetail.setTitle("Account Error");
return errorDetail;
}

if (exception instanceof AccessDeniedException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(403), exception.getMessage());
errorDetail.setProperty("description", "You are not authorized to access this resource");
errorDetail.setProperty(descField, "You are not authorized to access this resource");
errorDetail.setTitle("Authorization Error");
return errorDetail;
}

if (exception instanceof SignatureException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(403), exception.getMessage());
errorDetail.setProperty("description", "The JWT signature is invalid");
errorDetail.setProperty(descField, "The JWT signature is invalid");
errorDetail.setTitle("JWT Error");
return errorDetail;
}

if (exception instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException ex = (MethodArgumentNotValidException) exception;
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), "Validation error");
errorDetail.setProperty("description", "The request body is invalid");
errorDetail.setProperty(descField, "The request body is invalid");
errorDetail.setTitle("Validation Error");

Map<String, String> fieldErrors = new HashMap<>();
Expand All @@ -74,56 +74,56 @@ public ProblemDetail handleSecurityException(Exception exception) {
if (exception instanceof HttpMessageNotReadableException) {
HttpMessageNotReadableException ex = (HttpMessageNotReadableException) exception;
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(400), "Malformed JSON request");
errorDetail.setProperty("description", ex.getMessage());
errorDetail.setProperty(descField, ex.getMessage());
errorDetail.setTitle("Malformed JSON Error");
return errorDetail;
}

if (exception instanceof ExpiredJwtException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(403), exception.getMessage());
errorDetail.setProperty("description", "The JWT token has expired");
errorDetail.setProperty(descField, "The JWT token has expired");
errorDetail.setTitle("JWT Error");
return errorDetail;
}

if (exception instanceof HttpRequestMethodNotSupportedException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(405), exception.getMessage());
errorDetail.setProperty("description", "The HTTP method is not supported");
errorDetail.setProperty(descField, "The HTTP method is not supported");
errorDetail.setTitle("Method Not Allowed");
return errorDetail;
}

if (exception instanceof ResourceNotFoundException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(404), exception.getMessage());
errorDetail.setProperty("description", "The resource was not found");
errorDetail.setProperty(descField, "The resource was not found");
errorDetail.setTitle("Resource Not Found");
return errorDetail;
}

if (exception instanceof EmailAlreadyExistsException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(409), exception.getMessage());
errorDetail.setProperty("description", "The email already exists");
errorDetail.setProperty(descField, "The email already exists");
errorDetail.setTitle("Conflict");
return errorDetail;
}

if (exception instanceof UserDeletionException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(500), exception.getMessage());
errorDetail.setProperty("description", "An error occurred while deleting the user");
errorDetail.setProperty(descField, "An error occurred while deleting the user");
errorDetail.setTitle("User Deletion Error");
return errorDetail;
}

if (exception instanceof NoResourceFoundException) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(404), exception.getMessage());
errorDetail.setProperty("description", "The resource was not found");
errorDetail.setProperty(descField, "The resource was not found");
errorDetail.setTitle("Resource Not Found");
return errorDetail;
}

if (errorDetail == null) {
errorDetail = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(500), exception.getMessage());
errorDetail.setProperty("description", "Unknown internal server error.");
errorDetail.setProperty(descField, "Unknown internal server error.");
errorDetail.setTitle("Internal Server Error");
}

Expand Down

0 comments on commit 931704c

Please sign in to comment.