我想處理異常,以便URL信息自動顯示給客戶端。是否有捷徑可尋?春季REST控制器的異常處理程序
<bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<!-- what property to set here? -->
</bean>
我想處理異常,以便URL信息自動顯示給客戶端。是否有捷徑可尋?春季REST控制器的異常處理程序
<bean id="outboundExceptionAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<!-- what property to set here? -->
</bean>
你有兩個選擇:
Spring Reference 15.9.1 HandlerExceptionResolver
春天了HandlerExceptionResolvers緩解,而你的請求是由控制器 匹配請求處理時發生意外 異常的痛苦。 HandlerExceptionResolvers有點類似 異常映射,您可以在Web應用程序 描述符web.xml中定義異常映射。但是,它們提供了一種更靈活的方式來處理 異常。它們提供有關在拋出異常時執行哪個處理程序 的信息。此外,在將請求轉發到另一個URL(與使用特定於servlet的異常映射相同的最終結果)之前,處理異常的編程方式爲您提供了更多用於響應 的選項。
的HandlerExceptionResolver有一個方法,包含你需要的一切:
HandlerExceptionResolver.resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex)
或者,如果你需要不同的控制器不同的處理程序:Spring Reference Chapter 15.9.2 @ExceptionHandler
@ExceptionHandler(IOException.class)
public String handleIOException(IOException ex, HttpServletRequest request) {
return "every thing you asked for: " + request;
}
短缺問題簡答
我是doin g以下絕招:
@ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
ModelAndView mv = new ModelAndView("redirect:errorMessage?error="+exception.getMessage());
return mv;
}
@RequestMapping(value="/errorMessage", method=RequestMethod.GET)
@Responsebody
public String handleMyExceptionOnRedirect(@RequestParamter("error") String error) {
return error;
}
作品完美無缺。
引用中的處理程序主題在這裏:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers –