쌓고 쌓다

consumes, produces와 Content-Type 예외 처리 방법 본문

프로그래밍/spring

consumes, produces와 Content-Type 예외 처리 방법

승민아 2024. 1. 25. 16:41

다른 친구가 앱을 만들고 나는 API 서버를 구축하고 있는데

 

친구가 API 요청시 정상적인 응답을 못주는 상황을 발견했다.

 

서버에서 요청을 처리하는 코드는 다음과 같다.

@PostMapping(value = "/locations/{locationId}/posters")
    public ResponseEntity<PosterResponse> addPoster(@Valid @RequestPart PosterRequest posterRequest,
                                                    @RequestPart(required = false) List<MultipartFile> files,
                                                    @PathVariable Long locationId,
                                                    @AuthenticationPrincipal(expression = "member") Member member) throws IOException
{...}

Multipart 타입을 @RequestPart를 사용해 처리하는 로직이다.

 

친구는 다음과 같이 POSTMAN으로 요청을 보냈다.

application/json으로 요청을 보냈기에 Multipart를 처리하는 코드에서 정상적으로 처리하지 못한 것이다.

그렇다고 예외를 잘 던져주지도 않았기에 API 사용자는 난처할 뿐이다.

 

 

그래서 서버에서 요청 컨텐츠 타입을 지정하고 예외를 던져주는 방법이 필요하다.

 

consumes를 사용하여 처리할 요청 Content-Type을 지정할 수 있다.

코드는 다음과 같다.

@PostMapping(value = "/locations/{locationId}/posters", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<PosterResponse> addPoster()
    {...}

 

consumes 속성값을 처리할 타입을 지정해주면 된다.

 

 

이제 컨텐츠 타입이 맞지 않으면 HttpMediaTypeNotSupportedException이 터질텐데

이 예외를 처리해주면 된다!

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public ResponseEntity<ErrorResponse> mediaTypeException(HttpMediaTypeNotSupportedException e) {
        ErrorResponse errorResponse = new ErrorResponse(ErrorCode.NOT_SUPPORTED_CONTENT_TYPE);
        return ResponseEntity
                .status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
                .body(errorResponse);
    }
}

 

 

Content-Type 예외 응답

 

 

 

produces는 응답으로 줄 타입을 지정하는 것으로

 

요청의 헤더에 Accept와 일치하면 응답을 정상적으로 보내준다.

 

즉 클라가 수용할 수 있는 타입을 Accept 헤더로 함께 요청하는데 이 Accept와

우리가 작성한 produces가 일치하면 정상적으로 처리해주는것이다.

 

쉽게 말하자면,

consumes는 클라가 서버로 보낼때 이 타입만 받겠다하는것이고

produces는 서버가 클라로 보낼때 이 타입으로 보내겠다하는것이다.

Comments