2017년 5월 10일 수요일

Spring Global Exception Handling

Spring에서 익센셥을 처리하기 위해 아래와 같이 Exception Handler를 설정할 수 있다.
해당 ControllerAdvice 설정을 통해, 서버 내부의 Exception을 실제 사용자가 알 수 있는
Exception response로 변환하여 응답을 줄 수 있다.

아래와 같이 내부에서 InternalError Exception이 발생하였을 때,
실제 사용자에게는 400 BAD_REQUEST 로 응답이 가게 설정할 수 있다.
해당 응답을 통해, 실제 user에게 API 관점에서 error 원인을 알게 할 수 있다.

@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(value = InternalError.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST,
            reason = "internal error exception")
    public void InternalErrorException() {
    }
}

- Exception 발생시 서버 응답

{
  "timestamp": 1494426563174,
  "status": 400,
  "error": "Bad Request",
  "exception": "java.lang.InternalError",
  "message": "internal error exception",
  "path": "/test"
}

전체 예제는 아래 주소에서 확인할 수 있다.

https://gitlab.com/shashaka/exception-handling-project

댓글 없음 :

댓글 쓰기