Spring Boot3 & Spring Framework 6 강의 ::Section.7 - 에러 응답 구조 체계적으로 만들기

suragryen·2024년 3월 12일
0

Udemy-Spring

목록 보기
17/25

에러 응답 구조 체계적으로 만들기

  1. error를 디테일하게 받을 수 있는 dto를 만들어준다
package com.in28minnutes.rest.webservices.restfulwebservices.exception;

import java.time.LocalDate;

public class ErrorDetails {
	
	private LocalDate timestamp;
	private String message;
	private String details;
	
	
	
	public ErrorDetails(LocalDate timestamp, String message, String details) {
		super();
		this.timestamp = timestamp;
		this.message = message;
		this.details = details;
	}
	
	public LocalDate getTimestamp() {
		return timestamp;
	}
	public void setTimestamp(LocalDate timestamp) {
		this.timestamp = timestamp;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getDetails() {
		return details;
	}
	public void setDetails(String details) {
		this.details = details;
	}
	
	
	@Override
	public String toString() {
		return "ErrorDetails [timestamp=" + timestamp + ", message=" + message + ", details=" + details + "]";
	}
	
	

}
  1. ResponseEntityExceptionHandler 클래스를 상속하여 확장해준다.
package com.in28minnutes.rest.webservices.restfulwebservices.exception;

import java.time.LocalDate;
import java.time.LocalDateTime;

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.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.in28minnutes.rest.webservices.restfulwebservices.user.UserNotFoundException;

@ControllerAdvice //이 클래스를 모든 컨트롤러에 적용, 이 프로젝트에 정의된 모든 컨트롤러, 테스트 컨트롤러를 대상으
//ExceptionHandler를 선언하는 클래스를 대상 
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{
	
	 
		@ExceptionHandler(Exception.class) //어떤 예외를 처리할것인지 정의 (Exception.class) = 발생한 모든 예외를 정의 
		public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) throws Exception {
			ErrorDetails errorDetails = new ErrorDetails(LocalDate.now(), 
					ex.getMessage(), request.getDescription(false));
			
			return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
			
		}
        
  1. API Tester로 없는 사용자를 검색해서 예외처리가 잘 되었는지 확인

업로드중..

  • 없는 사용자 아이디 412로 테스트

잘 되었음을 확인 할 수 있다
시간까지 체크하고 싶으면 LocalDate를 LocalDateTime으로 바꿔주면 됌

profile
블로그 이사중 ☃︎

0개의 댓글

관련 채용 정보