如何在Spring Boot @ResponseBody中返回404响应状态-方法返回类型为Response? [英] How to return 404 response status in Spring Boot @ResponseBody - method return type is Response?
本文介绍了如何在Spring Boot @ResponseBody中返回404响应状态-方法返回类型为Response?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将Spring Boot与基于@ResponseBody的方法结合使用,如下所示:
I'm using Spring Boot with @ResponseBody based approach like the following:
@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());
}
我尝试了一些典型的方法,例如:
I tried some typical approaches as:
res.setStatus(HttpStatus.NOT_FOUND.value());
新的ResponseEntity(HttpStatus.BAD_REQUEST);
res.setStatus(HttpStatus.NOT_FOUND.value());
new ResponseEntity(HttpStatus.BAD_REQUEST);
但是我需要返回响应.
如果视频为空,如何在此处返回404状态代码?
How to return here 404 status code if video is null?
推荐答案
创建带有@ResponseStatus(HttpStatus.NOT_FOUND)
批注的NotFoundException
类,并将其从控制器中抛出.
Create a NotFoundException
class with an @ResponseStatus(HttpStatus.NOT_FOUND)
annotation and throw it from your controller.
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found")
public class VideoNotFoundException extends RuntimeException {
}
这篇关于如何在Spring Boot @ResponseBody中返回404响应状态-方法返回类型为Response?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文