restful

Exception 처리 심화과정 ..

hellojava 2023. 8. 13. 14:09

전 글에서 404에러를 해보았다. 

한 메서드에 대해서만 에러처리를 했었는데 이번엔 AOP를 활용하여 에러처리를 해볼것이다.

//AOP -> 로깅, 로그인, 메시지추가 등의 비즈니스로직에서
//항상 실행시켜줘야하는 로직이 있다면 aop..?

우선 예외처리를 하기 위해 예외발생한 시간정보와, 예외가 발생한 메세지, 예외의 상세 정보를 볼 것이다.

 

@Data
@AllArgsConstructor //모든 매개변수가 있는 생성자
@NoArgsConstructor// 기본 생성자
public class ExceptionResponse {
private Date timestamp;
private String message;
private String details;
}

간단히 만들었다.

 

그 다음 컨트롤러를 만들어

 

@RestController
@ControllerAdvice //모든 컨트롤러가 실행될떄 이게 실행됨
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

}

@ControllerAdvide 어노테이션을 추가하면 모든 컨트롤러가 실행될때 커스터마이즈핸들러가 실행될 것이다.

예외가 발생한다면 내가 지정한 에러를 만들 수 있다.

 

@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllException(Exception ex, WebRequest request) {
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);//500
}

ex -> 에러객체 

request -> 어디서 에러 났는지..

 

@ExceptionHandler(Excetion.class)

 

이렇게 하면 어떠한 컨트롤러가 실행되더라도 custumized~~ 핸들러가 실행 될것이고

 

이 클래스 안에서 exception이 발생된다면  핸들올익셉션을 실행시킨다 .

 

유저목록에 없는 5번유저로 요청을 보내면 500에러가 나고 내가 지정했던 설명이 나온다.

 

하지만 나는 4XX 에러가 필요하기 떄문에 하나 만들어야ㄷ한다.

 

@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이 발생하면 404에러를 내라는 코드를 만들었다.