例外のインターセプト

ログ出力インターセプトの続きとして例外発生時のインターセプトの実装。
これもdiconは一切弄る必要なくできる。

インターセプト

/**
 * 例外発生時にメール送信するクラス.
 *
 * @author zoi
 *
 */
public class MyThrowableInterceptor extends ThrowsInterceptor {
	/** シリアルバージョン. */
	private static final long serialVersionUID = 5306143265122341227L;

	/** サーブレットへのリクエスト内容. */
	public HttpServletRequest request;

	/**
	 * 例外インターセプター.
	 *
	 * @param e           スローされた例外内容
	 * @param invocation  スロー元のメソッド名
	 * @return            エラーページのファイル名
	 * @throws Throwable  スローされる例外
	 */
	public final String handleThrowable(final Exception e, final MethodInvocation invocation) throws Throwable {

		Utils.procException(request, e);

		return "/error.jsp";
	}
}

Utils.java
	/**
	 * 例外発生時にエラーページを表示してメール送信.
	 *
	 * @param request リクエスト内容
	 * @param e       スローされた例外内容
	 */
	public static void procException(final HttpServletRequest request, final Exception e) {
		ActionMessages errors = new ActionMessages();

		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.exception"));
		ActionMessagesUtil.addErrors(request, errors);

		// 例外詳細内容を取得
		StringWriter sw = new StringWriter();
	    PrintWriter pw = new PrintWriter(sw);
	    e.printStackTrace(pw);

	    // 呼び出し関数を取得
	    String[] methods = request.getParameterValues("SAStruts.method");
		String method = "";
		if (methods != null) {
			method = "/" + methods[0];
		}

	    String body = "";
	    body += "リクエスト元\n";
	    body += request.getRequestURI() + method + "\n\n";
	    body += "リクエスト内容\n";
		try {
			body += Utils.getAllParameter(request);
		} catch (Exception e1) {
			e.printStackTrace();
		}
	    body += "=====================================================================\n";
	    try {
			body += Utils.getAllHeader(request);
		} catch (Exception e1) {
			e.printStackTrace();
		}
	    body += "=====================================================================\n";
	    body += sw.toString();

	    // 例外を標準出力へ
	    e.printStackTrace();

		MailTransfer.send(body);
	}

error.jsp
<font color="red">
	<ul>
		<li>想定外のエラーが発生しました。エラー内容を管理人にメールしました。解決までしばらくお待ちください。</li>
	</ul>
</font>

後はポイントカットするクラスに

@Aspect("myThrowableInterceptor")
public class IndexAction {

とすれば出来上がり。設定ファイルがなくなることでかなり楽になるけれども、初めの第一歩はやはり大変です^^;

追記:
 サーバにcooldeployで更新したら、NULLPOINTER例外が・・・多分requestがDIされていない?
そのようなことがNETにはいろいろあるんで試行錯誤してみたけれども、解決できなかった・・・
とりあえずhotdeployでサーバを更新して対応・・・