반응형
Spring Boot @Response Body에서 404 응답 상태를 반환하는 방법 - 메서드 반환 유형은 Response입니까?
다음과 같은 @ResponseBody 기반 접근법과 함께 Spring Boot을 사용하고 있습니다.
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public @ResponseBody Response getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res) {
Video video = null;
Response response = null;
video = videos.get(id - 1);
if (video == null) {
// TODO how to return 404 status
}
serveSomeVideo(video, res);
VideoSvcApi client = new RestAdapter.Builder()
.setEndpoint("http://localhost:8080").build().create(VideoSvcApi.class);
response = client.getData(video.getId());
return response;
}
public void serveSomeVideo(Video v, HttpServletResponse response) throws IOException {
if (videoDataMgr == null) {
videoDataMgr = VideoFileManager.get();
}
response.addHeader("Content-Type", v.getContentType());
videoDataMgr.copyVideoData(v, response.getOutputStream());
response.setStatus(200);
response.addHeader("Content-Type", v.getContentType());
}
다음과 같은 일반적인 접근방식을 시도했습니다.
res.setStatus(HttpStatus).NOT_FOUND.value();
새로운 ResponseEntity(HttpStatus).BAD_REQUEST);
하지만 난 응답을 돌려줘야 해.
비디오가 null일 경우 404 상태 코드를 반환하려면 어떻게 해야 합니까?
이것은, 다음과 같이 간단하게 실시할 수 있습니다.
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);
호환성이 있습니다.@ResponseBody그리고 모든 반환값과 함께.Spring 5 이상 필요
작성하다NotFoundException과의 클래스@ResponseStatus(HttpStatus.NOT_FOUND)주석을 컨트롤러에서 던질 수 있습니다.
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found")
public class VideoNotFoundException extends RuntimeException {
}
원래 메서드는 다음을 반환할 수 있습니다(메서드 동작을 변경하지 않음).
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res{
...
}
다음 항목을 반환하십시오.
return new ResponseEntity(HttpStatus.NOT_FOUND);
responseStatus를 다음과 같이 설정할 수 있습니다.
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id,
HttpServletResponse res) {
...
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
// or res.setStatus(404)
return null; // or build some response entity
...
}
언급URL : https://stackoverflow.com/questions/25422255/how-to-return-404-response-status-in-spring-boot-responsebody-method-return-t
반응형
'programing' 카테고리의 다른 글
| SQL Server에서 선행 0을 트리밍하기 위한 더 나은 기술 (0) | 2023.04.08 |
|---|---|
| 원격 SQL Server 데이터베이스를 로컬 드라이브에 백업하려면 어떻게 해야 합니까? (0) | 2023.04.08 |
| Spring Boot에서 Web Client Mono를 사용하여 API 응답 오류 메시지 가져오기 (0) | 2023.04.03 |
| $resource 콜백(오류 및 성공) (0) | 2023.04.03 |
| wp rest api는 메타로 게시물을 가져옵니다. (0) | 2023.04.03 |