How to return 404 response status in Spring Boot @ResponseBody - method return type is Response?

catch23 picture catch23 · Aug 21, 2014 · Viewed 85.6k times · Source

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());
new ResponseEntity(HttpStatus.BAD_REQUEST);

but I need to return Response.

How to return here 404 status code if video is null?

Answer

andrej picture andrej · Feb 5, 2019

This is very simply done by throwing org.springframework.web.server.ResponseStatusException:

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

It's compatible with @ResponseBody and with any return value. Requires Spring 5+