Spring 中 REST 控制器的异常处理程序

fas*_*ava 3 aop spring exception spring-mvc

我想处理异常,以便 URL 信息自动显示给客户端。是否有捷径可寻?

<bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <!-- what property to set here? -->
</bean>
Run Code Online (Sandbox Code Playgroud)

Ral*_*lph 5

你有两个选择:

Spring参考15.9.1 HandlerExceptionResolver

Spring HandlerExceptionResolvers 可以减轻在与请求匹配的控制器处理请求时发生的意外异常的痛苦。HandlerExceptionResolvers 有点类似于您可以在 Web 应用程序描述符 web.xml 中定义的异常映射。然而,它们提供了一种更灵活的方式来处理异常。它们提供有关抛出异常时正在执行哪个处理程序的信息。此外,处理异常的编程方式为您提供了更多选择,以便在将请求转发到另一个 URL 之前做出适当的响应(与使用 servlet 特定异常映射时的最终结果相同)。

HandlerExceptionResolver有一种方法,包含您需要的一切

HandlerExceptionResolver.resolveException(HttpServletRequest request,
              HttpServletResponse response,
              Object handler, Exception ex) 
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要针对不同控制器的不同处理程序:Spring Reference Chapter 15.9.2 @ExceptionHandler

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

短问短答