我正在将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状态代码?
创建NotFoundException带有@ResponseStatus(HttpStatus.NOT_FOUND)注释的类,然后将其从控制器中抛出。
NotFoundException
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found") public class VideoNotFoundException extends RuntimeException { }