如何在休息控制器中抛出异常

San*_*age 1 java rest exception-handling

我想从控制器抛出一个异常.我怎样才能做到这一点?

@RequestMapping(value = "user", method = RequestMethod.POST, headers = "Accept=application/xml, application/json")
public @ResponseBody
AppUserDTO registerUser(@RequestBody AppUserDTO userDTO) {


        return userService.registerUser(userDTO);

}
Run Code Online (Sandbox Code Playgroud)

在此返回中,它将抛出异常.我可以使用任何类型的注释吗?如何将异常作为JSON传递给客户端?

Aur*_*and 5

您似乎正在使用Spring-MVC.存在少数异常,默认情况下映射到特定的HTTP错误代码.你可以在这里找到这些列表:

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-rest-spring-mvc-exceptions

您抛出的任何其他未捕获的异常都将导致HTTP 500响应.

有关如何在Spring中使用Exceptions的详细解答,我建议您详细阅读链接页面或google"Spring MVC Exception".