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

后端 未结 7 1941
别跟我提以往
别跟我提以往 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:09

    The easiest way to just set the response.setStatus(). Easy and clean, you can change it to any status you want just instead of ex.getStatusCode() add your code.

    The return type is also of your choice, I'm using String b/c displaying this later.

    By the way, the sendError is not a good idea, because JBoss for instance is adding a lot of HTML to the response.

    @ExceptionHandler(CommunicationException.class)
    @ResponseBody()
    public String handleCommunicationException(CommunicationException ex, HttpServletResponse response) throws IOException{
        response.setStatus(ex.getStatusCode());
        return ex.getStatusMessage();   
    }
    

提交回复
热议问题