日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

java spring异常处理_Java深入 - Spring 异常处理HandlerExceptionResolver

發(fā)布時(shí)間:2025/3/13 java 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java spring异常处理_Java深入 - Spring 异常处理HandlerExceptionResolver 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

spring的異常統(tǒng)一處理非常簡單,首先我們需要看一下Spring中定義的HandlerExceptionResolver接口:

/**

* Interface to be implemented by objects than can resolve exceptions thrown

* during handler mapping or execution, in the typical case to error views.

* Implementors are typically registered as beans in the application context.

*

*

Error views are analogous to the error page JSPs, but can be used with

* any kind of exception including any checked exception, with potentially

* fine-granular mappings for specific handlers.

*

* @author Juergen Hoeller

* @since 22.11.2003

*/

public interface HandlerExceptionResolver {

/**

* Try to resolve the given exception that got thrown during on handler execution,

* returning a ModelAndView that represents a specific error page if appropriate.

*

The returned ModelAndView may be {@linkplain ModelAndView#isEmpty() empty}

* to indicate that the exception has been resolved successfully but that no view

* should be rendered, for instance by setting a status code.

* @param request current HTTP request

* @param response current HTTP response

* @param handler the executed handler, or null if none chosen at the

* time of the exception (for example, if multipart resolution failed)

* @param ex the exception that got thrown during handler execution

* @return a corresponding ModelAndView to forward to,

* or null for default processing

*/

ModelAndView resolveException(

HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);

}

他定義了一個(gè)resolveException方法,我們?nèi)绻幚懋惓5脑?#xff0c;需要實(shí)現(xiàn)這個(gè)接口類,并且實(shí)現(xiàn)resolveException方法,在resolveException方法中處理自己的異常邏輯。 例如我設(shè)計(jì)一個(gè)自定義的異常處理類:

/**

* 自定義一個(gè)異常捕獲處理類

* @author zhuli

* @date 2014-9-3

*/

public class MyExceptionResolver implements HandlerExceptionResolver {

private static final Logger logger = LoggerFactory.getLogger(MyExceptionResolver.class);

@Override

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

//可以自由處理各種異常邏輯

if (ex instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {

logger.warn(Logger.ACTION.DEFAULT, "Http Method Error");

}

return null;

}

}

然后需要將我們的我們自定義的MyExceptionResolver類注入到bean中

具體Spring是怎么調(diào)用的?我們可以先看下Spring中的doDispatch方法中,有這么一段代碼:

catch (ModelAndViewDefiningException ex) {

logger.debug("ModelAndViewDefiningException encountered", ex);

mv = ex.getModelAndView();

}

catch (Exception ex) {

Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);

mv = processHandlerException(processedRequest, response, handler, ex);

errorView = (mv != null);

}

其中processHandlerException方法就是來捕獲異常處理的,那么繼續(xù)看processHandlerException這個(gè)方法:

protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,

Object handler, Exception ex) throws Exception {

// Check registered HandlerExceptionResolvers...

ModelAndView exMv = null;

for (HandlerExceptionResolver handlerExceptionResolver : this.handlerExceptionResolvers) {

exMv = handlerExceptionResolver.resolveException(request, response, handler, ex);

if (exMv != null) {

break;

}

}

if (exMv != null) {

if (exMv.isEmpty()) {

return null;

}

// We might still need view name translation for a plain error model...

if (!exMv.hasView()) {

exMv.setViewName(getDefaultViewName(request));

}

if (logger.isDebugEnabled()) {

logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv, ex);

}

WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());

return exMv;

}

throw ex;

}

這個(gè)方法中的handlerExceptionResolver.resolveException就是用來捕獲異常的,并且Spring允許多個(gè)自定義的異常類實(shí)現(xiàn)。 可以看this.handlerExceptionResolvers方法,跟蹤進(jìn)去

private void initHandlerExceptionResolvers(ApplicationContext context) {

this.handlerExceptionResolvers = null;

if (this.detectAllHandlerExceptionResolvers) {

// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.

Map matchingBeans = BeanFactoryUtils

.beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);

if (!matchingBeans.isEmpty()) {

this.handlerExceptionResolvers = new ArrayList(matchingBeans.values());

// We keep HandlerExceptionResolvers in sorted order.

OrderComparator.sort(this.handlerExceptionResolvers);

}

}

else {

try {

HandlerExceptionResolver her =

context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);

this.handlerExceptionResolvers = Collections.singletonList(her);

}

catch (NoSuchBeanDefinitionException ex) {

// Ignore, no HandlerExceptionResolver is fine too.

}

}

// Ensure we have at least some HandlerExceptionResolvers, by registering

// default HandlerExceptionResolvers if no other resolvers are found.

if (this.handlerExceptionResolvers == null) {

this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);

if (logger.isDebugEnabled()) {

logger.debug("No HandlerExceptionResolvers found in servlet '" + getServletName() + "': using default");

}

}

}

可以清洗看到這個(gè)方法是將handlerExceptionResolvers進(jìn)行了初始化,并將自定義的異常處理類(可以多個(gè))寫入this.handlerExceptionResolvers

總結(jié)

以上是生活随笔為你收集整理的java spring异常处理_Java深入 - Spring 异常处理HandlerExceptionResolver的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。