카테고리 없음
HTTP 를 이해하고 중복 코드를 없애봅시다.
lluna
2022. 2. 3. 22:22
해당 예외 처리 클래스의 문제점은 무엇일까요?
바로 중복이 있다는 것입니다.
BAD_REQUEST 가 무려 3 번이나 등장했습니다.
HTTP 구조를 이해할 필요가 있습니다.
Spring ResponseEntity 의 정의입니다.
public class ResponseEntity<T>
extends HttpEntity<T>
쓰임입니다.
@RequestMapping("/handle")
public ResponseEntity<String> handle() {
URI location = ...;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(location);
responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
즉, body에 status 를 넣지 않아도 Status Line 에 데이터가 반환 되겠군요.
코드를 리팩토링 해봅시다.
리팩토링 전
@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler (AlreadyExistNicknameException.class)
protected ResponseEntity<Object> handleAlreadyExistNickname(AlreadyExistNicknameException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("statusValue", HttpStatus.BAD_REQUEST.value());
body.put("status", HttpStatus.BAD_REQUEST);
body.put("errors", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler (AlreadyExistEmailException.class)
protected ResponseEntity<Object> handleAlreadyExistEmail(AlreadyExistEmailException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("statusValue", HttpStatus.BAD_REQUEST.value());
body.put("status", HttpStatus.BAD_REQUEST);
body.put("errors", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
리팩토링 후
@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler (AlreadyExistNicknameException.class)
protected ResponseEntity<Object> handleAlreadyExistNickname(AlreadyExistNicknameException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("errors", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler (AlreadyExistEmailException.class)
protected ResponseEntity<Object> handleAlreadyExistEmail(AlreadyExistEmailException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("errors", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
이해하기 명확한 HTTP Response 가 리턴 되겠습니다.