In Spring 3 is it possible to dynamically set the reason of @ResponseStatus?

后端 未结 7 1934
别跟我提以往
别跟我提以往 2021-02-05 02:01

I have a custom exception class annotated to return a given HttpStatus:

@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason=\"Invalid parameter\")
         


        
7条回答
  •  伪装坚强ぢ
    2021-02-05 02:10

    The correct way is to introduce exception handler in your controller, then you can set response body of any status code:

    @Controller
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public class SomeController {
    ...
      @ExceptionHandler(BadRequestException.class)
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      public @ResponseBody
       Map handleIndexNotFoundException(BadRequestException bre,
                                               HttpServletRequest request, HttpServletResponse resp) {
         HashMap result = new HashMap<>();
         result.put("error", true);
         result.put("error_message", bre.getMessage());
         return result;
      }
    }
    

    Move over you don't have to pollute your model/exception classes with any Spring Web MVC annotations and dependency.

    If you want to share the handler with all controller look into @ControllerAdvice.

提交回复
热议问题