如何在Spring Boot @ResponseBody中返回404响应状态-方法返回类型为Response?

问题描述 投票:25回答:4

我正在将Spring Boot与基于@ResponseBody的方法结合使用,如下所示:

@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);

但是我需要返回Response

如果视频为空,如何在这里返回404状态代码?

java spring http-status-code-404 retrofit
4个回答
54
投票
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found") public class VideoNotFoundException extends RuntimeException { }

24
投票
ResponseEntity

24
投票
org.springframework.web.server.ResponseStatusException

3
投票
© www.soinside.com 2019 - 2024. All rights reserved.