在Spring 3中,可以动态设置@ResponseStatus的原因吗?


问题内容

我有一个自定义的异常类,被注释为返回给定的HttpStatus

@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid parameter")
public class BadRequestException extends RuntimeException
{
  public BadRequestException(String msg)
  {
    super(msg);
  }
}

当我BadRequestException从控制器中抛出a时,此方法有效,但原因当然总是“无效参数”。有没有办法在此类中设置返回的原因?我想传递一个字符串用作原因。

谢谢!


问题答案:

您可以使用HttpServletResponsesendError功能来实现。
这是一个如何使用它的示例:

@RequestMapping(value = "some/url", method = RequestMethod.POST)
public void doAction(final HttpServletResponse response) throws IOException {
  response.sendError(HttpStatus.BAD_REQUEST.value(), "custom error message");
}