Как крупномасштабные приложения систематически настраивают сообщения об ошибках с соответствующими кодами для всех своих API с использованием Spring Boot и Java, особенно если они имеют более 100 различных сообщений об ошибках, сопоставленных с кодами состояния HTTP?
Вместо обработки каждого исключения в каждом методе API существует ли более общий подход, например @ControllerAdvice? Каковы недостатки использования @ControllerAdvice, особенно в отношении порядка обработчиков исключений?
@GetMapping("/user/{id}")
public ResponseEntity getUserById(@PathVariable String id) {
List userInfoByIdList = null;
try {
userInfoByIdList = userService.getUserById(id);
if (userInfoByIdList.isEmpty()) {
throw new NoUserFoundException("No user found with ID: " + id);
}
if (userInfoByIdList.get(0).isDeleted()) {
throw new UserDeletedException("User with ID: " + id + " has been deleted");
}
if (!userService.isUserEligible(userInfoByIdList.get(0))) {
throw new UserNotEligibleForAccessingUserException("User with ID: " + id + " is not eligible for access");
}
} catch (NoUserFoundException e) {
log.error("NoUserFoundException while fetching user for ID {}: {}", id, e.getMessage(), e);
return new ResponseEntity(new UserResponse(HttpStatus.NOT_FOUND.value(), e.getMessage()),
HttpStatus.NOT_FOUND);
} catch (UserDeletedException e) {
log.error("UserDeletedException while fetching user for ID {}: {}", id, e.getMessage(), e);
return new ResponseEntity(new UserResponse(HttpStatus.GONE.value(), e.getMessage()),
HttpStatus.GONE);
} catch (UserNotEligibleForAccessingUserException e) {
log.error("UserNotEligibleForAccessingUserException while fetching user for ID {}: {}", id, e.getMessage(), e);
return new ResponseEntity(new UserResponse(HttpStatus.FORBIDDEN.value(), e.getMessage()),
HttpStatus.FORBIDDEN);
} catch (ServiceException e) {
log.error("ServiceException while fetching user for ID {}: {}", id, e.getMessage(), e);
return new ResponseEntity(new UserResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()),
HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
log.error("Error while fetching user for ID {}: {}", id, e.getMessage(), e);
return new ResponseEntity(new UserResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()),
HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity(new UserResponse(HttpStatus.OK.value(), userInfoByIdList), HttpStatus.OK);
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... plications