How to respond with HTTP status code in a Spring MVC @RestController @ResponseBody class returning an object?

后端 未结 2 1675
萌比男神i
萌比男神i 2020-12-23 11:57

I\'m trying to have a @RestController which takes a @PathVariable return a specific object in JSON format, along with proper status code. So far th

2条回答
  •  不思量自难忘°
    2020-12-23 12:45

    The idiomatic way would be to use an exception handler instead of catching the exception in your regular request handling method. The type of exception determines the response code. (403 for security error, 500 for unexpected platform exceptions, whatever you like)

    @ExceptionHandler(MyApplicationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleAppException(MyApplicationException ex) {
      return ex.getMessage();
    }
    
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleAppException(Exception ex) {
      return ex.getMessage();
    }
    

提交回复
热议问题