Spring 심화 1주차(5)

신성훈·2024년 6월 19일
0

TIL

목록 보기
41/162
post-thumbnail

오늘의 학습 키워드

  • API 예외처리

API 예외처리

  • 예외 처리가 필요한 이유
    -웹 애플리케이션의 “예외”에 대하여 다시 한 번 인지할 필요가 있다. 웹 애플리케이션에서의 에러를 Client와 Server 모두가 잘 알지 못하면, 서비스하는 환경에서 발생하는 에러에 대해서 제대로 대응 할 수 없다.
    -에러를 처리하는 것 역시 관심사를 분리해서 더 효율적으로 처리 할 수 있지 않을까 고민해보는 시간이 필요하기 때문이다.
  • HTTP 상태 코드 종류
    -2xx Success → 200번대의 상태코드는 성공을 의미!
    -4xx Client Error → 400번대의 상태코드는 클라이언트 에러, 즉 잘못된 요청을 의미!
    -5xx Server Error → 500번대의 상태코드는 서버 에러, 즉 정확한 요청에 서버쪽 사유로 에러가 난 상황을 의미!
    -> Spring에서는 아래와 같은 아주 편리한 enum도 제공하고 있다. HttpStatus


  • Spring 예외처리 방법

  1. Controller 코드 수정
    -ResponseEntity는 HTTP response object 를 위한 Wrapper이다. 아래와 같은 것들을 담아서 response로 내려주면 아주 간편하게 처리가 가능하다.
    -HTTP status code
    -HTTP headers
    -HTTP body
@PostMapping("/folders")
public ResponseEntity<RestApiException> addFolders(@RequestBody FolderRequestDto folderRequestDto,
								@AuthenticationPrincipal UserDetailsImpl userDetails) {
	try {
		List<String> folderNames = folderRequestDto.getFolderNames();

		folderService.addFolders(folderNames, userDetails.getUser());
		return new ResponseEntity<>(HttpStatus.OK);
	} catch(IllegalArgumentException ex) {
		RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
		return new ResponseEntity<>(
			// HTTP body
			restApiException,
			// HTTP status code
			HttpStatus.BAD_REQUEST);
	}
}
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(
		 // HTTP body
		restApiException,
		// HTTP status code
		HttpStatus.BAD_REQUEST);

-> 에러문구 캐치하고, 그에 따라서 어느 부문에서 오류가 났는지 적어서 보내 줄 수 있다.

  1. @ExceptionHandler 사용
  • FolderController 의 모든 메서드에 예외처리 적용 (AOP) : @ExceptionHandler
    -@ExceptionHandler 는 Spring에서 예외처리를 위한 애너테이션이다.
    -이 애너테이션은 특정 Controller에서 발생한 예외를 처리하기 위해 사용
    -@ ExceptionHandler 가 붙어있는 메서드는 Controller에서 예외가 발생했을 때 호출 되며, 해당 예외를 처리하는 로직을 담고 있다.
    -AOP를 이용한 예외처리 방식이기때문에, 위에서 본 예시처럼 메서드 마다 try catch할 필요없이 깔금한 예외처리가 가능하다.
  • @ExceptionHandler 예외처리 추가
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<RestApiException> handleException(IllegalArgumentException ex) {
	RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
	return new ResponseEntity<>(
			// HTTP body
			restApiException,
			// HTTP status code
			HttpStatus.BAD_REQUEST
	);
}
profile
조급해하지 말고, 흐름을 만들고, 기록하면서 쌓아가자.

0개의 댓글