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

查看:41
本文介绍了Spring 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 应用程序中定义的异常映射描述符 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;
}

简答题

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

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