Home > Software design >  How do I set the HttpStatus code when using @ResponseBody?
How do I set the HttpStatus code when using @ResponseBody?

Time:12-04

In a SpringBoot Controller class, my APIs usually return a ResponseEntity with a body and a status code. But I can apparently dispense with the ResponseEntity by annotating my controller method with @ResponseBody, like this:

@Controller
public class DemoController 
{
  @Autowired
  StudentService studentService;

  @GetMapping("/student")
  @ResponseBody
  Student getStudent(@RequestParam id) {
    return studentService.getStudent(id);
  }
}

If my service throws an exception, I can return a custom HTTP status by throwing a ResponseStatusException, but it's not clear how to specify the HTTP status for a valid response. How would I specify this? Or how does it decide what to use?

CodePudding user response:

If you use the @ResponseBody annotation, the return type of the controller method will be used as the response body. The HTTP status code will default to 200 (OK) if the controller method completes successfully, or 500 (Internal Server Error) if an exception is thrown.

You can specify a custom HTTP status code by throwing a ResponseStatusException with the desired status code. For example:

@Controller
public class DemoController 
{
  @Autowired
  StudentService studentService;

  @GetMapping("/student")
  @ResponseBody
  Student getStudent(@RequestParam id) {
    if (id == null) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing required parameter 'id'");
    }
    return studentService.getStudent(id);
  }
}

CodePudding user response:

Probably the better way to handle it there is your custom ExceptionHandler:

@Controller
public class DemoController {
    @Autowired
    StudentService studentService;

    @GetMapping("/student")
    @ResponseStatus(HttpStatus.OK)
    Student getStudent(@RequestParam id) {
        return studentService.getStudent(id);
    }

    @ExceptionHandler(StudentNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    ErrorResponse handleStudentNotFoundException(StudentNotFoundException ex) {
        return new ErrorResponse("Student not found with id: "   ex.getId());
    }
}

read more: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

  • Related