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

后端 未结 4 1136
醉梦人生
醉梦人生 2021-01-30 20:24

I\'m using Spring Boot with @ResponseBody based approach like the following:

@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public @Respons         


        
相关标签:
4条回答
  • 2021-01-30 20:33

    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 {
    }
    
    0 讨论(0)
  • 2021-01-30 20:38

    Your original method can return ResponseEntity (doesn't change your method behavior):

    @RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
    public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res{
    ... 
    }
    

    and return the following:

    return new ResponseEntity(HttpStatus.NOT_FOUND);
    
    0 讨论(0)
  • 2021-01-30 20:39

    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+

    0 讨论(0)
  • 2021-01-30 20:53

    You can just set responseStatus on res like this:

    @RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
    public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id,
                                                HttpServletResponse res) {
    ...
        res.setStatus(HttpServletResponse.SC_NOT_FOUND); 
        // or res.setStatus(404)
        return null; // or build some response entity
     ...
    }
    
    0 讨论(0)
提交回复
热议问题