例外処理のアイデア
フレームワークを学ぶ前に、どのように例外に対処しますか?try-catch
。
これには2つの欠点があります。1つはtry
ビジネスロジックコードがモジュールに記述されることが多く、ビジネス処理と例外処理が一緒に結合されることです。もう1つは、catch
モジュールが例外情報を出力するように記述されることが多く、ユーザーにこの情報が表示されることです。経験は非常に貧弱です。
SpringMVCフレームワークはそれを巧みに切り離します:
Daoレイヤー、Serviceレイヤー、Controllerレイヤーで例外が発生しました。レイヤーごとにスローすることを躊躇せず、最終的に、Unifiedの例外ハンドラー(ExceptionResolver)を呼び出すフロントコントローラー(DispatcherServlet)に例外がスローされました。処理。
例外処理の2つの実装
①SpringMVCフレームワークが提供する単純な例外ハンドラSimpleMappingExceptionResolverを使用する
②独自の手書きのカスタム例外ハンドラーを使用し、HandlerExceptionResolverインターフェースを実装します
単純なマッピング例外ハンドラー(フレームワークによって提供される)
例外ごとに、対応するエラービューにジャンプします。すべては、ユーザーが見るページをより親しみやすくすることです。
<!-- 配置简单映射异常处理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 默认错误页面 -->
<property name="defaultErrorView" value="error_0.jsp" />
<!-- 各种异常及其对应错误视图 -->
<property name="exceptionMappings">
<map>
<entry key="java.lang.NullPointerException" value="error_1.jsp" />
<entry key="java.lang.RuntimeException" value="error_2.jsp" />
<entry key="java.io.IOException" value="error_3.jsp" />
<entry key="java.io.FileNotFoundException" value="error_4.jsp" />
<entry key="java.sql.SQLException" value="error_5.jsp" />
<!-- More kinds of Exceptions... -->
</map>
</property>
</bean>
カスタムマッピング例外ハンドラー(自分で手書き)
例外ごとに、エラービューにジャンプできるだけでなく、いくつかの情報を添付することもできます。
HandlerExceptionResolverインターフェースを実装する手書きの例外ハンドラー:
public class MyExceptionResolver implements HandlerExceptionResolver {
// 关键参数:异常对象Exception
// 返回值:跳转的错误视图信息ModelAndView
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if(e instanceof java.lang.NullPointerException) {
modelAndView.addObject("xxx", "xxxxxxx");
modelAndView.setViewName("error_1.jsp");
} else if(e instanceof java.lang.RuntimeException) {
modelAndView.addObject("xxx", "xxxxxxx");
modelAndView.setViewName("error_2.jsp");
} else if(e instanceof java.io.IOException) {
modelAndView.addObject("xxx", "xxxxxxx");
modelAndView.setViewName("error_3.jsp");
} else if(e instanceof java.io.FileNotFoundException) {
modelAndView.addObject("xxx", "xxxxxxx");
modelAndView.setViewName("error_4.jsp");
} else if(e instanceof java.sql.SQLException) {
modelAndView.addObject("xxx", "xxxxxxx");
modelAndView.setViewName("error_5.jsp");
} else {
modelAndView.addObject("xxx", "xxxxxxx");
modelAndView.setViewName("error_0.jsp");
}
return modelAndView;
}
}
次に、フレームワークに次のように伝えます。
<!-- 配置自定义异常处理器 -->
<bean class="com.samarua.resolver.MyExceptionResolver" />