扱いたい例外と処理

  1. エラーコードなどがきちんと整理できているシステムを作る際には、よく以下のような例外をつくります。
     public class SystemException extends RuntimeException{
       private String errid;
       private String[] msgs;
       
       public String getErrid(){ return errid; }
       public String[] getMsgs(){ return msgs; }
     
       public SystemException(String pErrid, String[] pMsgs){
         super(pErrid);
         errid = pErrid;
         msgs = pMsgs;
       }
     
       public SystemException(String pErrid, String[] pMsgs, Throwable cause){
         super(pErrid,cause);
         errid = pErrid;
         msgs = pMsgs;
       }
       
       public SystemException(String pErrid, String msg1){
         SystemException(pErrid, new String[]{msg1});
       }
     
       public SystemException(String pErrid, String msg1, Throwable cause){
         SystemException(pErrid, new String[]{msg1}, cause);
       }
     
       …(以下msg2,msg3,msg4,...をとれるコンストラクタがつづく)
     }
    
  2. Struts側で、この例外が出たら無条件でシステムエラー画面に遷移するようにしたい。
  3. このとき例外に格納されているメッセージを表示するようにしたい。

例外ハンドラの作成

  1. 独自の例外ハンドラを作成して、ActionMessagesにメッセージを登録するようにします。基本的に org.apache.struts.action.ExceptionHandler? の execute メソッドをそのまま使ます。(*印のついているところが変更箇所)
     public class SystemExceptionHandler extends ExceptionHandler{
       /** commons-logging */
       private static Log logger = LogFactory.getLog(SystemExceptionHandler.class);
       
       public ActionForward execute(
         Exception ex,
         ExceptionConfig ae,
         ActionMapping mapping,
         ActionForm formInstance,
         HttpServletRequest request,
         HttpServletResponse response)
         throws ServletException {
       
         ActionForward forward = null;
         ActionMessage error = null;
         String property = null;
         
         // Build the forward from the exception mapping if it exists
         // or from the form input
         if (ae.getPath() != null) {
           forward = new ActionForward(ae.getPath());
         } else {
           forward = mapping.getInputForward();
         }
         
         // Figure out the error
         if (ex instanceof ModuleException) {
           error = ((ModuleException) ex).getActionMessage();
           property = ((ModuleException) ex).getProperty();
     *   } else if (ex instanceof SystemException) {
     *     error = new ActionMessage(((SystemException) ex).getErrId(), ((SystemException) ex).getMsgs());
     *     property = error.getKey();
         } else {
           error = new ActionMessage(ae.getKey(), ex.getMessage());
           property = error.getKey();
         } 
       
         this.logException(ex);
       
         // Store the exception
         request.setAttribute(Globals.EXCEPTION_KEY, ex);
         this.storeException(request, property, error, forward, ae.getScope());
       
         return forward;
       }
     }
    
  2. struts-config.xml への登録は以下のようにします
    <global-exceptions>
      <exception
        type="com.foo.SystemException"
        path="/syserr.jsp"
        handler="com.foo.SystemExceptionHandler" />
    </global-exception>

アプリケーション実行例

  1. Action(から呼び出されたモジュール)内でSystemException?がおきます
     class OrderDAO {
       public OrderVO findByPK( String orderNo ){
         .....
         throw new SystemException("syserr.duplicate","ORDER_TBL",orderNo);
         .....
       }
     }
    
  2. SystemExceptionHandler?が動いて、エラーメッセージがセットされます
  3. システムエラー画面に遷移します
     <%@ page contentType="text/html;charset="Shift_JIS" language="java" %>
     <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
     
     <html:html>
     <head><title>System Error</title>
     <body>
     <h1>申し訳ありません、システムエラーが発生しました</h1>
     システム管理課にご連絡下さい(内線番号 xxxx-xxxx)<br/>
     <br/>
     <html:errors>
     </body>
     </html:html>
    
  4. エラーメッセージは、application.properties にプレイスホルダー付きで用意されているものが使われます
    syserr.duplicatie=プライマリキーが重複しています。テーブル名:{0} , 登録キー:{1}

例外ハンドラにパラメータを与えたい時

  1. 独自のExceptionConfigクラスを作成する
     public class SystemExceptionConfig extends ExceptionConfig{
       protected String errLevel;
       
       public String getErrLevel(){
         return errLevel;
       }
       public void setErrLevel( String param ){
         errLevel = param;
       }
     }
    
  2. struts-config.xml に定義する
    <global-exceptions>
      <exception
        type="com.foo.SystemException"
        path="/syserr.jsp"
        handler="com.foo.SystemExceptionHandler"
        classname="com.foo.SystemExceptionConfig">
        
        <set-property
          property="errLevel"
          value="fatal" />
      
      </excetion>
    </global-exception>
  3. 例外ハンドラでの扱い
     public class SystemExceptionHandler extends ExceptionHandler{
       /** commons-logging */
       private static Log logger = LogFactory.getLog(SystemExceptionHandler.class);
       
       public ActionForward execute(Exception ex,
                                    ExceptionConfig ec,
                                    ActionMapping mapping,
                                    ActionForm form,
                                    HttpServletRequest req,
                                    HttpServletResponse res)
                                      throws ServletException{
         long errRefId = System.currentTimeMillis();
         
         logMsg = "System Error Occured(#" + errRefId + ")"
        
         SystemExceptionConfig conf = (SystemExceptionConfig)ec;
         if( "fatal".equals( conf.getErrLevel() ) ){
           logger.fatal(logMsg, ex);
         }else if("warn".equals( conf.getErrLevel() ) ){
           logger.warn(logMsg, ex);
         
         (以下略)
    

Java#Struts


トップ   編集 凍結解除 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2006-04-15 (土) 23:35:56 (6583d)
Short-URL: https://at-sushi.com:443/pukiwiki/index.php?cmd=s&k=b5d34e8e18
ISBN10
ISBN13
9784061426061