---
title: "转:自定义异常处理"
author: "kkcheng"
date: "2011-06-01T10:15:51Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2011-06-01T10:15:51Z"
id: 1066950
url: "https://kkcheng.iteye.com/blog/1066950"
---

此统一处理的目的在于 Web层、Service层抛出的业务异常以统一的格式显示在页面的固定位置。

首先定义我们的业务异常类。

public abstract class BaseException extends RuntimeException {
    private static final long serialVersionUID = -6765360320533958383L;

    private String messageCode;

    public String getMessageCode() {
        return messageCode;
    }

    public void setMessageCode(String messageCode) {
        this.messageCode = messageCode;
    }

    public BaseException() {
        super();
    }

    public BaseException(String message) {
        super(message);
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseException(Throwable cause) {
        super(cause);
    }

    public BaseException(String messageCode, String message) {
        super(message);
        setMessageCode(messageCode);

    }

    public BaseException(String messageCode, String message, Throwable cause) {
        super(message, cause);
        setMessageCode(messageCode);
    }

public class BusinessException extends BaseException {

    private static final long serialVersionUID = -1657938434382769721L;
                   
    public BusinessException() {
        super();
    }
    
    public BusinessException(String message, Throwable cause) {
        super(message, cause);
    }
    
    public BusinessException(Throwable cause) {
        super(cause);
    }
    
    public BusinessException(String messageCode, String message) {
        super(messageCode, message);
        setMessageCode(messageCode);
    }
    
    public BusinessException(String messageCode, String message, Throwable cause) {
        super(messageCode, message, cause);
        setMessageCode(messageCode);
    }
}


拦截器类：ErrorHandlingInterceptor.java 用于拦截异常，并在此统一处理
public class ErrorHandlingInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = 1L;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        try {
            return invocation.invoke();
        } catch (Exception e) {
            e.printStackTrace();
            handleException(e);
        }
        return Action.INPUT;
    }
    
    /** *//**
     * 处理异常
     * @param e
     */
    private void handleException(Exception e) {
        boolean handled = false;
        Throwable throwEx = e;
        while (throwEx != null) {
            if(throwEx instanceof BusinessException) {
                BusinessException be = (BusinessException)throwEx;
                String errorCode = be.getMessageCode();
                
                // 从缓存中通过ErrorCode取得对应message
                // 实现略
                String errorMsg = getMessage(errorCode);
                
                // 页面显示错误提示信息
                fillError4Display(errorMsg);
                handled = true;
            } 
            throwEx = throwEx.getCause();
        }
        
        if(!handled) {
            fillDefaultError();
        }
    }
    
    private HttpServletRequest getRequest() {
        return (HttpServletRequest)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
    }
    
    private void fillDefaultError() {
        fillError4Display("系统忙，请稍候再试。");
    }
    
    private void fillError4Display(String msg) {
        getRequest().setAttribute("_error_msg_", msg);
    }
}

拦截所有的异常，并对其进行处理。
当为 自定义的BusinessException时，根据抛出异常时的msgCode，取得对应的显示信息。
msgCode与显示信息的对应关系 可先配置好，系统启动时将其缓存起来。

如果非BusinessException，则统一显示为 “系统忙，请稍候再试。”

将要显示的信息设置到Request中，下面来看看Freemarker模板的写法：

msg.ftl


<div id='_err_msg_div'>
    <#if Request?exists>
        ${Request}
    </#if>
</div>

<script type="text/javascript">
if (!this.Message) {
    this.Message = {};
    (function() {
        /**//**
         * show client message
         */
        Message.showMsg = function(msg) {
            document.getElementById("_err_msg_div").innerHTML = msg;
        };
    })();
};
</script>
在使用时，只要在页面上想要展现异常信息的地方插入如下代码即可：
<#include "/msg.ftl">

这样 系统中的异常 将会被统一的显示。

当使用js做前台的表单验证的时候，提示用户的输入有问题，则可以使用 Message.showMsg('...')，提示信息也会显示在同一个位置。

这样就实现了异常提示信息的统一展示了。

这是一个比较简易的实现，只提供一个思路。