在Spring 3中是否可以动态设置@ResponseStatus的原因?
我有一个自定义的exception类注释返回给定的HttpStatus
:
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid parameter") public class BadRequestException extends RuntimeException { public BadRequestException(String msg) { super(msg); } }
这在我从我的控制器抛出BadRequestException
时起作用,但原因当然是“无效参数”。 有没有办法在这个类中设置返回的原因? 我想传递一个字符串作为原因。
谢谢!
你可以使用response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid foo");
正确的方法是在控制器中引入exception处理程序,然后可以设置任何状态代码的响应主体:
@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; } }
移动您不必使用任何Spring Web MVC注释和依赖项污染您的模型/exception类。
如果你想与所有控制器共享处理程序,请查看@ControllerAdvice 。
如果在自定义exception的@ResponseStatus注释中省略’reason’属性,
@ResponseStatus(value = HttpStatus.CONFLICT) // 409 public class ChildDataExists extends RuntimeException { ...
然后抛出exception
throw new ChildDataExists("Can't delete parent if child row exists.");
exception消息作为JSON输出中“数据”的“消息”传递。 似乎注释中的“原因”会覆盖自定义行为。
注释是静态的,不能从您的类动态设置。 我建议为每种类型的故障情形创建BadRequestException
的子类,并以不同方式对它们进行注释。
这不仅仅是一种解决方法 – 如果你隐藏了关于reason
消息中出错的细节,那么你就会失去灵活性,因为任何捕获BadRequestException
代码都必须处理所有相同的故障情况办法。
设置response.setStatus()
的最简单方法。 简单而干净,您可以将其更改为您想要的任何状态,而不是ex.getStatusCode()
添加您的代码。
返回类型也是您的选择,我正在使用String b / c稍后显示。
顺便说一句, sendError
不是一个好主意,因为JBoss例如在响应中添加了大量的HTML。
@ExceptionHandler(CommunicationException.class) @ResponseBody() public String handleCommunicationException(CommunicationException ex, HttpServletResponse response) throws IOException{ response.setStatus(ex.getStatusCode()); return ex.getStatusMessage(); }
“reason”是可选的,因此您可以省略它并实现抽象方法public String reason传递Error。 链接: http : //static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html