java 如何在休息控制器中抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16160293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to throw exceptions in rest controllers
提问by Sanjaya Liyanage
I want to throw an exception from the controller. How can I do that?
我想从控制器抛出异常。我怎样才能做到这一点?
@RequestMapping(value = "user", method = RequestMethod.POST, headers = "Accept=application/xml, application/json")
public @ResponseBody
AppUserDTO registerUser(@RequestBody AppUserDTO userDTO) {
return userService.registerUser(userDTO);
}
In this return it will throw an exception. Is there any kind of annotation I could use? How will the exception be passed to the client side as JSON?
在此返回中,它将抛出异常。我可以使用任何类型的注释吗?异常将如何作为 JSON 传递给客户端?
回答by Aurand
You appear to be using Spring-MVC. There exist a handful of exceptions which, by default, map to specific HTTP error codes. You can find a list of these here:
您似乎正在使用 Spring-MVC。默认情况下,存在一些映射到特定 HTTP 错误代码的异常。您可以在此处找到这些列表:
Any other uncaught exception you throw will result in a HTTP 500 response.
您抛出的任何其他未捕获的异常都将导致 HTTP 500 响应。
For a detailed answer on how to use Exceptions with Spring, I suggest you read the linked page in detail or google "Spring MVC Exception".
有关如何在 Spring 中使用异常的详细答案,我建议您详细阅读链接页面或谷歌“Spring MVC 异常”。
回答by Agustí Sánchez
More examples on exception handling in this blog: http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html
此博客中有关异常处理的更多示例:http: //www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html
Examples refer to Spring Boot but apply to plain Spring REST as well.
示例指的是 Spring Boot,但也适用于普通的 Spring REST。