엄지월드

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation 본문

카테고리 없음

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

킨글 2022. 9. 2. 08:59

REST API 만들때 아래와 같은 에러를 만났다.

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

 

이유는 return ResponseEntity.ok().body()에서 데이터 하나밖에 넘겨줄 수 밖에 없기 때문에 

return ResponseEntity.ok.body("test");와 같이 넘겨주면 작동하지만

return ResponseEntity.ok.body(responseResult);로 넘겨주면 작동하지 않고 위에 에러가 발생하는 것이었다.  

즉, 핸들러 입장에서 클라이언트가 요청한 타입으로 응답을 내려줄 수 없는 에러였다. 

 

package com.gworld.manage.controller;

import com.gworld.manage.common.model.ResponseResult;
import com.gworld.manage.model.BoardDto;
import com.gworld.manage.model.ServiceResult;
import com.gworld.manage.service.NoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
public class ApiNoticeController {
    private final NoticeService noticeService;

    @PostMapping("/api/notice/del.api")
    public ResponseEntity<?> del(
            @RequestBody BoardDto boardDto
    ){
        ServiceResult result = noticeService.delete(boardDto.getId());
        if(!result.isResult()){
            ResponseResult responseResult = new ResponseResult(false, result.getMessage());
            return ResponseEntity.ok().body(responseResult);
        }
        ResponseResult responseResult = new ResponseResult(true);
        return ResponseEntity.ok().body(responseResult);
    }
}

그래서 ResponseResult에 @Data를 추가해주어 Getter를 처리하였다. 

package com.gworld.manage.common.model;

import lombok.Data;

@Data
public class ResponseResult {
    ResponseResultHeader header;
    Object body;
    public ResponseResult(boolean result, String message){
        header = new ResponseResultHeader(result, message);
    }
    public ResponseResult(boolean result){
        header = new ResponseResultHeader(result);
    }
}

 

Comments