Notice
Recent Posts
Recent Comments
Link
«   2026/09   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

helloworld

Exception 처리 본문

restful

Exception 처리

hellojava 2023. 8. 13. 13:30

이전까지 get과 post로 데이터를 넣고 확인하고 해봤다.

 

내가 안썼던거 같은데

 

users/{id}라는 엔드포인트로 특정 유저번호로 유저에 대한 상세 정보를 보는 코드를 만들었었다.

 

하지만 users에 없는 id값을 넣게 되면 어떻게 될까..

 

유저는 3번까지밖에 없는 상황인데 200 ok Status code를 받았다.

 

때문에 Exception 처리를 해볼 것이다.

 

우선 Http의 Status Code를 알아야 할 것 같다.

 

2XX - > Ok

4XX - > Client

5XX - > Server

 

200으로 시작되는 코드는 요청이 잘 됐다는 뜻이고

400으로 시작되는 코드는 클라이언트쪽 즉 요청을 잘못 했다는 뜻이고

500으로 시작되는 코드는 서버쪽에서 데이터 처리르 잘 못했다는 뜻이다.

 

@GetMapping("/users/{id}")
public User retrieveUser(@PathVariable int id) {
User user = service.findOne(id);

return user;
}

기존 이런 코드에 

 

Exception 코드를 추가해 보자..

 

if (user == null) {
throw new UserNotFoundException(String.format("ID[%s] not found",id));
}

만약 유저가 없다면 

 

UserNotFoundException이라는 클래스로 던지는 코드다 

 

get요청시 들어온 id값이 [%s] 안으로 들어가서 만약 users/100이라고 요청을 넣었다면

 

ID[100] not found 라는 코드가 나올 것이다.

 

UserNotFoundException 이라는 클래스를 만든 후에

 

public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}

부모 클래스로 message를 다시 주는 간단한 메서드다.

 

하지만 이렇게 해서 코드를 실행해보면 

 

500에러가 나온다. 

 

{
    "timestamp""2023-08-13T04:25:56.859+00:00",
    "status"500,
    "error""Internal Server Error",
    "trace""너무 길어서 자름"
    "message""ID[5] not found",
    "path""/users/5"
}

이건 클라이언트쪽에서 요청을 잘못한거기 때문에 4-- 에러가 나와야 한다.

 

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

@ResponseStatus 어노테이션을 추가하여 상태를 넣어주면

 

{
    "timestamp""2023-08-13T04:29:50.640+00:00",
    "status"404,
    "error""Not Found",
    "trace""너무 길어요",
    "message""ID[5] not found",
    "path""/users/5"
}

404 not found로 에러처리를 완료하였다

'restful' 카테고리의 다른 글

DELETE 기능  (0) 2023.08.13
Exception 처리 심화과정 ..  (0) 2023.08.13
rest PostMapping 2  (0) 2023.08.13
restful PostMapping  (0) 2023.08.13
RESTful 프로젝트?  (0) 2023.08.13