Struts1.3.5の例外ハンドリング手法
Strutsのドキュメント(4.4.1 Action Class Design Guidelines)を読んでいて発見したのだけれど、
Don’t throw it, catch it!
らしい。Actionクラスでは例外を投げず、全てキャッチしろ!ってことだと思う。Runtimeを拾うかどうかは好みなのかもしれないが、拾っておいたほうがいいかもね。
ExceptionHandler
struts-config.xmlのglobal-exceptionsを使えば、例外のハンドリングが可能。web.xmlのerror-pageでも可能だが、こちらは「エラーが発生してからの処理」をHandlerクラスで行うことができる。ログ出力とかをまとめることができるね。
参考:
ExceptionHandler
public class AppExceptionHandler extends ExceptionHandler {
@Override public ActionForward execute( Exception e, ExceptionConfig conf, ActionMapping map, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws ServletException {
//ログ出力のかわりにprintStackTrace System.out.println("AppExceptionHandlerで制御"); e.printStackTrace();
return super.execute(e, conf, map, form, req, res); }}
struts-config.xml
<global-exceptions> <exception key="errors.9999" type="java.lang.Exception" path="/error50X.jsp" handler="com.daipresents.struts135.action.AppExceptionHandler" /> </global-exceptions>
handler属性で
ちなみに、web.xmlとstruts-config.xmlで同じ例外を指定していた場合は、struts-config.xmlが勝つらしい。
注意点
さらに、global-exceptionsはJSP上のエラーは無視する(なぜじゃ)。なので、保険のために、web.xmlの上でもerror-pageを指定しておくほうがいい。JSPでのエラーをひろって、ログに出力できるのであればこれ使うけどねー。
web.xml
<error-page> <exception-type>java.lang.Exception</exception-type> <location>/error50X.jsp</location> </error-page>




