Skip to content

02 ‐ ExceptionHandler 사용시 ErrorResponse 사용

Ryu(Paul) edited this page Sep 24, 2023 · 1 revision
@ExceptionHandler(value = NotFoundException.class)
public ResponseEntity notFoundException(HttpServletRequest req, NotFoundException e) {
    ErrorResponse errorResponse = new ErrorResponse(req, HttpStatus.NOT_FOUND, e);
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
}

위와 같이 ExceptionHandler 작성 하실 때 리스폰스 바디에 좀 더 디테일한 정보들을 담기 위해 ErrorResponse를 만들었습니다.

public class ErrorResponse {

    public ErrorResponse(HttpServletRequest req, HttpStatus httpStatus, Exception exception) {
        this.timestamp = (LocalDateTime.now());
        this.statusCode = httpStatus.value();
        this.statusText = httpStatus.getReasonPhrase();
        this.message = exception.getMessage();
        this.path = req.getRequestURI();
    }

    private final LocalDateTime timestamp;
    private final int statusCode;
    private final String statusText;
    private final String message;
    private final String path;
}

HttpServletRequest, HttpStatus, Exception를 인자로 받는 생성자가 있어서 위에 코드 참고하셔서 객체 생성하시고 바디에 담아주시면 됩니다.