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

我正在使用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());
新响应实体(HttpStatus.BAD_REQUEST);

但我需要返回响应

如果视频为空,如何返回此处404状态代码?


答案 1

这很简单,只需抛出 org.springframework.web.server.ResponseStatusException 即可:

throw new ResponseStatusException(
  HttpStatus.NOT_FOUND, "entity not found"
);

它与任何返回值兼容,并与任何返回值兼容。需要春季 5+@ResponseBody


答案 2

创建一个带有注释的类,并将其从控制器中抛出。NotFoundException@ResponseStatus(HttpStatus.NOT_FOUND)

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found")
public class VideoNotFoundException extends RuntimeException {
}

推荐