다음은 간단한 유저를 저장하는 코드이다.
@RestController
public class UserController {
private UserDaoService service;
public UserController(UserDaoService service) {
this.service = service;
}
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
return service.findOne(id);
}
}
매우 간단한다. 아이디를 받아서, 해당 아이디가 있으면 그정보를 반환한다.
하지만, 만약 아이디에 해당하는값이 없다면?
public User save(User user) {
if (user.getId() == null) {
user.setId(++userCount);
}
users.add(user);
return user;
}
위 코드에 따르면, id에 값이 없으면 null을 반환한다.
그러면 client는 null과 함께,정사적인 반환을 했다고 200코드를 반환한다.
아닛... 뭔가 이상하다. 없는 정보를 반환했는데, 200코드라고 정상적이라고 반환하는것이..
그래서 예외시켜보자.
@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
User user = service.findOne(id);
if (user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found",id));
}
return user;
}
조건문을 추가해서, 만약 찾은 user가 null 이라면, 내가 직접 만든 예외를 보내겠다.
예외문 인자값은 예외와 함께 보낼 message이다.
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// HTTP Status code
// 2XX -> ok
// 4XX -> Client fault
// 5XX -> Server fault
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
다음은 간단하게 만드는 나만의 예외이다.
@ResponseStatus로 적당한 예외를 찾는다. 그 중에서 not found(404)를 찾았고.
RuntimeException 을 상속을 받아, super()로 상속 마무리를 한다.
그리고 다시 값을 찾아보면~
404에러가 정삭적으로 나온다.
잘려서 안나오지만, message도 "ID[100] not found" 로 잘 출력된다.
-정리-
평소 모든 처리를 200코드 처리를 하다가, 이렇게 상태코드를 변환시키는 것을 배워보았다.
한층 더 발전함을 느낀다. 앞으로도 자주 사용해 보겠다.
'RESTful' 카테고리의 다른 글
Rest API version 관리(URI) (0) | 2022.01.16 |
---|---|
@JsonFilter (0) | 2022.01.16 |
@JsonIgnore (jackson) (0) | 2022.01.16 |
Internationalization 다국어처리 (0) | 2022.01.15 |
Validation (0) | 2022.01.14 |