春天的REST控制器异常处理程序 [英] Exception handler for REST controller in spring

查看:174
本文介绍了春天的REST控制器异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要处理异常,因此URL信息会自动显示给客户端。有没有办法做到这一点?

I want to handle exceptions so the URL information is automatically shown to the client. Is there an easy way to do this?

<bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <!-- what property to set here? -->
</bean>


推荐答案

您有两种选择:

Spring参考15.9.1 HandlerExceptionResolver


Spring HandlerExceptionResolvers缓解了在您的请求时发生的意外
异常的痛苦由与控制器匹配的控制器
处理。 HandlerExceptionResolvers有点类似于
您可以在web应用程序
descriptor web.xml中定义的异常映射。但是,它们为
处理异常提供了一种更灵活的方式。当抛出异常时,它们提供有关
处理程序执行的信息。此外,一个程序化的
处理异常的方法可以让您在将请求转发到另一个URL之前适当地响应
(与使用servlet特定异常映射时相同的
最终结果) 。

Spring HandlerExceptionResolvers ease the pain of unexpected exceptions that occur while your request is handled by a controller that matched the request. HandlerExceptionResolvers somewhat resemble the exception mappings you can define in the web application descriptor web.xml. However, they provide a more flexible way to handle exceptions. They provide information about which handler was executing when the exception was thrown. Furthermore, a programmatic way of handling exceptions gives you more options for responding appropriately before the request is forwarded to another URL (the same end result as when you use the servlet specific exception mappings).

HandlerExceptionResolver 有一种方法,其中包含您需要的所有内容:

The HandlerExceptionResolver has one method, containing everything you need:

HandlerExceptionResolver.resolveException(HttpServletRequest request,
              HttpServletResponse response,
              Object handler, Exception ex) 

或者如果您需要不同控制器的不同处理程序: Spring引用第15.9.2节@ExceptionHandler

Or if you need different handlers for different controllers: Spring Reference Chapter 15.9.2 @ExceptionHandler

@ExceptionHandler(IOException.class)
public String handleIOException(IOException ex, HttpServletRequest request) {
   return "every thing you asked for: " + request;
}

短问题简答

这篇关于春天的REST控制器异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆