이번에는 일반화된 예외클래스를 사용하도록 생성해보려고 한다.
예외 클래스를 처리하기 위해 Exception Response라는 JAVA POJO 객체를 선언하고 발생 시간, 메시지, 상세정보와 같은 내용을 선언하려고 한다.
package com.example.restfulwebservice.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExceptionResponse {
private Date timestamp;
private String message;
private String details;
}
우선 Exception 패키지를 만들고 ExceptionResponse 클래스를 생성해준다.
ResponseEntitiyExceptionHandler 라는 클래스를 상속받은 새로운 Handler 클래스를 만들어 볼것이다.
스프링 프레임워크에서 로그인 정보나 메시지 정보들, 비즈니스 로직 등 컨트롤러에서 실행시켜야 하는 공통적인 부분이 있다면 AOP를 활용하여 실행시킬 수 있다.
package com.example.restfulwebservice.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestController
@ControllerAdvice
public class CustomizedResponseEntitiyExceptionHandler extends ResponseEntityExceptionHandler {
}
@ControllerAdvice를 활용하면 모든 컨트롤러가 실행될때 어노테이션을 가지고 있는 빈이 사전에 실행되도록 되어있다.
에러가 발생하면 등록시켜놓은 에러메시지가 실행되기도 한다.
package com.example.restfulwebservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.Date;
@RestController
@ControllerAdvice
public class CustomizedResponseEntitiyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request){
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
//발생 시점, 어떤 오류 메시지인지, 어떤 설명인지
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
이렇게 Exception 클래스를 생성해 준 후 어떠한 메시지를 실행시킬것인지 설정해준다.
Postman에서 확인해보면 500번 에러 코드와 message, timestamp, details를 출력하는 것을 볼 수 있다.
이 메서드는 모든 예외처리를 해주는 메서드이다.
그래서 이번에는 일반화되어있는 모든 Exception이 아닌 사용자가 존재하지않았을때 처리할 수 있는 UserNotFoundException을 생성해놓았기 때문에 이를 이용하여 예외처리를 해보려고 한다.
package com.example.restfulwebservice.exception;
import com.example.restfulwebservice.User.UserNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.Date;
@RestController
@ControllerAdvice
public class CustomizedResponseEntitiyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request){
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
//발생 시점, 어떤 오류 메시지인지, 어떤 설명인지
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR); //status code 500번
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request){
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND); //404 코드
}
}
메서드를 우리가 만들어놓은 UserNotFoundException을 이용하여 예외처리를 한 후 Postman에서 확인을 해보면 500번 코드가 아닌 404코드가 나타나는 것을 확인 할 수 있다.
'프로그래밍 > SPRING BOOT' 카테고리의 다른 글
[인프런 : spring-boot] 유효성 체크를 위한 Validation API (0) | 2022.09.01 |
---|---|
[인프런 : spring-boot] DELETE-HTTP Method (0) | 2022.08.30 |
[인프런 : spring-boot] HTTP Status Code 제어/예외처리 활용 (0) | 2022.08.30 |
[인프런 : spring-boot] POST-HTTP Method (0) | 2022.08.30 |
[인프런 : spring-boot] User 도메인 클래스 생성 / GET HTTP Method (0) | 2022.08.30 |