Spring Boot3 & Spring Framework 6 강의 ::Section.8 - 예외 처리 구현하기 - 404 Resource Not found

suragryen·2024년 3월 11일
0

Udemy-Spring

목록 보기
15/25

존재하지 않는 사용자를 검색했을때 예외처리를 해보자!🧑🏻‍🏫

  • Optional.get에서 예외가 발생함.

  • 조건에 맞는 항목이 없음
  • 벨류가 존재하면 값을 리턴하고 아니면 예외를 발생시킨다.
	Predicate<? super User> predicate = user -> user.getId().equals(id);
		return  users.stream().filter(predicate).findFirst().orElse(null);
  • .findFirst().orElse(null);
  • 결과가 없을경우 화면에 아무것도 뜨지 않는다.

예외처리 해주기

  1. UserResource.java
	@GetMapping("/users/{id}")
	public User retrieveUsers(@PathVariable int id){
		User user = service.findOne(id);
		
		if(user==null)
			throw new UserNotFoundException("id:" + id);
		
		
		return service.findOne(id); 
	} 
  1. UserNotFoundException.java
public class UserNotFoundException extends RuntimeException {
	public UserNotFoundException (String message) {
		super(message);
	}
}
  • RuntimeException을 상속해준다

  • 에러를 정확히 확인할 수 있다

404에러로 바꿔주기

보통 존재하지 않는건 404페이지 처리를 해주기 때문에(지금은 500) 404로 바꿔준다

@ResponseStatus 추가

@ResponseStatus(code = HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
	public UserNotFoundException (String message) {
		super(message);
	}
}

변경 완료!

*devtools를 주석처리해주면 로그가 짧게 뜸

profile
블로그 이사중 ☃︎

0개의 댓글

관련 채용 정보