-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[feat] : 3주차과제 수정 #6
Open
woals2840
wants to merge
1
commit into
main
Choose a base branch
from
week2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
📘UserRepositorypublic interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByEmail(String email);
}
✅회원가입 //UserController
@PostMapping("/user/signup")
ResponseEntity<String> signUp(@Valid @RequestBody SignupRequest signupRequest, BindingResult result){
if(result.hasErrors()){
List<String> errors = result.getAllErrors().stream()
.map(error -> error.getDefaultMessage())
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(String.join(", ", errors));
}
long userId = userService.signUp(signupRequest);
return ResponseEntity.created(URI.create(String.format("/user/signup/%d", userId)))
.build();
}
//UserService
@Transactional
public long signUp(SignupRequest req) {
Optional<UserEntity> userEntityOptional =
userRepository.findByEmail(req.getEmail());
if(userEntityOptional.isPresent()){
throw new CustomException(ErrorCode.EMAIL_ALREADY_EXISTS);
}
String name = req.getName();
String password = req.getPassword();
String email = req.getEmail();
String nickname = req.getNickname();
UserEntity newUser = new UserEntity(email, name, nickname, password);
userRepository.save(newUser);
return newUser.getUserId();
}
✅로그인 @PostMapping("user/login")
ResponseEntity<String> login(@Valid @RequestBody LoginRequest loginRequest){
UserEntity userEntity = userService.login(loginRequest.getEmail(), loginRequest.getPassword());
return ResponseEntity.ok()
.header("UserId", String.valueOf(userEntity.getUserId()))
.build();
}
public UserEntity login(String email, String password){
return userRepository.findByEmail(email)
.filter(userEntity -> password.equals(userEntity.getPassword()))
.orElseThrow(()-> new CustomException(ErrorCode.INVALID_USER));
}
✅일기 수정(기존코드 + 로그인) @PatchMapping("/diaries/{id}")
ResponseEntity<Void> patchDiary( @RequestHeader("User-Id") long userId,
@PathVariable final Long id, @RequestBody DiaryPatchRequest diaryPatchRequest){
diaryService.patchDiary(id, userId, diaryPatchRequest);
return ResponseEntity.ok().build();
}
public void patchDiary(final long id, long userId, DiaryPatchRequest diaryPatchRequest){
DiaryEntity diaryEntity = diaryRepository.findById(id).orElseThrow(()-> new RuntimeException("해당하는 일기가 없습니다"));
if(!diaryEntity.getUser().getUserId().equals(userId)){
throw new CustomException(ErrorCode.NON_AUTHORIZED);
}
String name = diaryPatchRequest.getName();
String content = diaryPatchRequest.getContent();
diaryEntity.setContent(content);
diaryEntity.setName(name);
diaryRepository.save(diaryEntity);
}
✅일기 삭제(기존코드 + 로그인) @DeleteMapping("/diaries/{id}")
ResponseEntity<Void> delete(@RequestHeader("User-Id") String userId, @PathVariable Long id){
Long parsedUserId = Long.parseLong(userId);
diaryService.deleteDiary(parsedUserId, id);
return ResponseEntity.noContent().build();
} public void deleteDiary(Long userId, Long id){
DiaryEntity diaryEntity = diaryRepository.findById(id).orElseThrow(()-> new RuntimeException("존재하지 않습니다"));
if(userRepository.findById(userId).isEmpty()){
throw new CustomException(ErrorCode.INVALID_USER);
} else if(!diaryEntity.getUser().getUserId().equals(userId)){
throw new CustomException(ErrorCode.NON_AUTHORIZED);
} else {
diaryRepository.deleteById(id);
}
}
✅일기 생성(기존코드 + 로그인) @PostMapping("/diaries")
ResponseEntity<DiaryResponse> post(@RequestHeader("User-Id") String userId,
@RequestBody DiaryCreateRequest diaryCreateRequest) {
//글자수 30자 제한
long parsedUserId = Long.parseLong(userId);
UserEntity user = userService.findById(parsedUserId);
if (diaryCreateRequest.getContent().length() > 30) {
throw new CustomException(ErrorCode.INVALID_SIZE);
}
else{
DiaryEntity savedDia = diaryService.createDiary(user, diaryCreateRequest.getTitle(), diaryCreateRequest.getContent(), diaryCreateRequest.getScope());
return ResponseEntity
.created(URI.create("/diaries" + savedDia.getId()))
.build();
}
}
public DiaryEntity createDiary(UserEntity userEntity, String title, String content, DiaryScope scope) {
DiaryEntity diaryEntity = new DiaryEntity(title, content, scope, LocalDate.now(), userEntity );
diaryRepository.save(diaryEntity);
return diaryEntity;
}
✅일기 조회(기존코드 + scope) public List<Diary> getList(){
//(1) repository로부터 DiaryEntity를 가져옴
final List<DiaryEntity> diaryEntityList = diaryRepository.findAll();
final List<Diary> diaryList = new ArrayList<>();
for(DiaryEntity diaryEntity : diaryEntityList){
if(diaryEntity.getScope().equals(DiaryScope.PRIVATE)){
continue;
}
diaryList.add(
new Diary(diaryEntity.getId(),diaryEntity.getName())
);
}
return new ArrayList();
}
✅예외처리에러코드(ENUM)
public enum ErrorCode {
EMAIL_ALREADY_EXISTS(HttpStatus.BAD_REQUEST,"40900","이메일 중복입니다" ),
NICK_ALREADY_EXISTS(HttpStatus.BAD_REQUEST, "40901", "닉네임 중복입니다"),
INVALID_EMAIL_TYPE(HttpStatus.UNAUTHORIZED, "40000", "이메일 형식이 올바르지 않습니다"),
INVALID_SIZE(HttpStatus.UNAUTHORIZED, "40001", "글자수를 확인하세요"),
INVALID_METHOD(HttpStatus.METHOD_NOT_ALLOWED, "40500", "지원하지 않는 HTTP 메소드입니다"),
INVALID_USER(HttpStatus.UNAUTHORIZED, "40100", "비밀번호가 잘못되었습니다"),
NON_AUTHORIZED(HttpStatus.UNAUTHORIZED, "40300", "권한이 없습니다");
private final HttpStatus httpStatus;
private final String errorCode;
private final String message;
public String getErrorCode() {
return errorCode;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
public String getMessage() {
return message;
}
ErrorCode(HttpStatus httpStatus, String errorCode, String message) {
this.httpStatus = httpStatus;
this.errorCode = errorCode;
this.message = message;
}
} GlobalExceptionHandler
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({CustomException.class, NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class})
public ResponseEntity<Object> handleException(Exception e){
HttpHeaders headers = new HttpHeaders();
HttpStatus status = determineStatus(e);
Map<String,Object> errors = new HashMap<>();
errors.put("Code", getCode(e) );
errors.put("ErrorMessage", getErrorMessage(e));
errors.put("Date", String.valueOf(new Date()));
return new ResponseEntity<>(errors, headers, status);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach(error -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
private HttpStatus determineStatus(Exception e){
if(e instanceof CustomException){
return ((CustomException) e).getErrorCode().getHttpStatus();
} else if (e instanceof NoHandlerFoundException){
return HttpStatus.NOT_FOUND;
} else if(e instanceof HttpRequestMethodNotSupportedException){
return HttpStatus.METHOD_NOT_ALLOWED;
}
return HttpStatus.INTERNAL_SERVER_ERROR;
}
private int getCode(Exception e){
if(e instanceof CustomException){
return ((CustomException) e).getHttpErrorCode();
}else if ( e instanceof NoHandlerFoundException){
return HttpStatus.NOT_FOUND.value();
}else if (e instanceof HttpRequestMethodNotSupportedException){
return HttpStatus.METHOD_NOT_ALLOWED.value();
}
return HttpStatus.INTERNAL_SERVER_ERROR.value();
}
private String getErrorMessage(Exception e){
if(e instanceof CustomException){
return ((CustomException) e).getErrorCode().getMessage();
} else if(e instanceof NoHandlerFoundException){
return "해당 요청을 찾을 수 없습니다";
} else if(e instanceof HttpRequestMethodNotSupportedException){
return "지원되지 않는 HTTP 메서드입니다";
}
return "Internal ServerError";
}
} CustomException(exception)
public class CustomException extends RuntimeException{
private final ErrorCode errorCode;
public ErrorCode getErrorCode() {
return errorCode;
}
public int getHttpErrorCode() {
return Integer.parseInt(errorCode.getErrorCode());
}
public CustomException(ErrorCode errorCode) {
this.errorCode = errorCode;
}
public CustomException(Throwable cause, ErrorCode errorCode) {
super(cause);
this.errorCode = errorCode;
}
public CustomException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}
public CustomException(String message, Throwable cause, ErrorCode errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, ErrorCode errorCode) {
super(message, cause, enableSuppression, writableStackTrace);
this.errorCode = errorCode;
}
} → ErrorCode 를 사용하여 에러코드를 정의하고 CustomException ㅇ에서 이를 활용하여 일관된 오류 처리와 응답을 보낼 수 있습니다. 이를 통해 코드의 가독성이 향상되며 유지보수가 쉬워집니다. → 또한 Service 계층에서 |
Parkjyun
reviewed
Nov 7, 2024
|
||
|
||
@Transactional | ||
public long signUp(SignupRequest req) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이거도 괜찮은데 따로 서비스용 dto 만드는 것도 알아보세요
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
No description provided.