WEB/Spring

Best Practice For Error Hadling , REST API Error Response

쿠마쿠마34 2022. 8. 14. 00:01
반응형

🌟

REST API Erorr Handling

📌HTTP Status Code

서버는 무조건 클라이언트에게 해당 요청이 제대로 처리 되었는지 아닌지를 알려주어야 한다. 그를 위해 사용하는 것이 HTTP Status Code.

크게는 5가지 상태 값으로 분류된다.

  1. 100-level(Informational) → 서버가 요청을 알아들었다.
  1. 200-level(Success) → 서버가 요청을 기대한대로 처리하였다.
  1. 300-level(Redirection) → 요청을 처리하려면 client의 추가적인 작업이 필요하다.
  1. 400-level(Client Error) → client가 잘못된 요청을 보냈다.
  1. 500-level(Server Error) → 유효한 요청이지만 서버단에서 처리할 때 문제가 발생했다.

📍자주 쓰이는 상태 코드

  • 400(Bad Request)
    • 클라이언트가 잘못된 요청을 보낸 경우이다. 예를 들면 필요한 request body 나 parameter가 빠졌을 경우
  • 401(Unauthorized)
    • client가 인증을 받는데 실패했다.
  • 404(Not Found)
    • 요청한 주소가 올바르지 않은 경우
  • 412(Precondition Failed)
    • Request Header의 필드 값이 한 개 이상 잘못된 경우
  • 500(Internal Server Error)
    • 일반적인 서버 에러
  • 503(Service Unvailable)
    • 요청한 서비스를 처리 불가능

📌Default Spring Error Response

{
    "timestamp":"2019-09-16T22:14:45.624+0000",
    "status":500,
    "error":"Internal Server Error",
    "message":"No message available",
    "path":"/api/book/1"
}

→ Error가 발생했을 때 기본적으로 스프링에서 제공하는 에러 리턴 타입

이 정보만으로 부족하다면, 우리는 필요한 정보들을 더 추가해서 제공할 수 있다.

📌Best Practice for error response body

대부분의 REST API 들이 이 형태를 따라서 Error를 Response한다.

{
    "type": "/errors/incorrect-user-pass",
    "title": "Incorrect username or password.",
    "status": 403,
    "detail": "Authentication failed due to incorrect username or password.",
    "instance": "/login/log/abc123"
}
  • type : 에러를 분류하기 위한 식별자
  • title : 간단한 에러 메시지
  • statuas : HTTP 응답 코드
  • detail : 더 자세한 에러에 대한 설명
  • instance : 에러가 발생한 URI

 

📌Reference

반응형