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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:04:08  来源:igfitidea点击:

How to throw exceptions in rest controllers

javarestexception-handling

提问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 错误代码的异常。您可以在此处找到这些列表:

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

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

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。