1. 程式人生 > >統一異常管理

統一異常管理

一、自定義異常處理器


import com.jd.y.saas.gauze.message.MessageHelper;


public class GauzeException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	/**
	 * 錯誤程式碼
	 */
	private String errorCode;
	private Object[] args;

	public GauzeException() {
	}
	public GauzeException(Throwable cause) {
		super(cause);
	}	
	public GauzeException(String errorCode) {
		super(getResourceMessage(errorCode));
		this.errorCode = errorCode;
	}
	public GauzeException(String errorCode, Object... args) {
		super(getResourceMessage(errorCode, args));
		this.errorCode = errorCode;
		this.args = args;
	}
	public GauzeException(Throwable cause, String errorCode, Object... args) {
		super(getResourceMessage(errorCode, args), cause);
		this.errorCode = errorCode;
		this.args = args;
	}

	public String getErrorCode() {
		return errorCode;
	}
	public Object[] getArgs() {
		return args;
	}
	
	private static String getResourceMessage(String errorCode) {
		String message = errorCode;
		try {
			message = MessageHelper.getMessage(errorCode);
		} catch (Exception e) {
		}
		return message;
	}
	private static String getResourceMessage(String errorCode, Object... args) {
		String message = errorCode;
		try {
			message = MessageHelper.getMessage(errorCode, args);
		} catch (Exception e) {
		}
		return message;
	}

}

MessageHelper類

import java.text.MessageFormat;
import java.util.Locale;

/**
 * 描述:
 * 日誌國際化包裝類
 */
public class MessageHelper extends BaseMessage {


    /**
     * @param key 屬性主鍵
     * @return 訊息內容
     */
    public static String getMessage(final String key) {
    	return getResourceBundle().getString(key);
    }

    /**
     * @param key 屬性主鍵
     * @param lang 語言環境
     * @return 訊息內容
     */
    public static String getMessage(final String key, final Locale locale) {
    	return getResourceBundle(locale).getString(key);
    }

    /**
     * @param key 屬性主鍵
     * @return 訊息內容
     */
    public static String getMessage(final String key, final Object... args) {
    	return MessageFormat.format(getMessage(key), args);
    }

    /**
     * @param key 屬性主鍵
     * @param lang 語言環境
     * @return 訊息內容
     */
    public static String getMessageInNoCurrentThread(final String key, final Locale locale, final Object... args) {
    	return MessageFormat.format(getMessage(key, locale), args);
    }
}

BaseMessage類

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 描述:
 * 日誌國際化基礎類
 */
public class BaseMessage {

    public static final String PREFIX_LOGGER_FILE = "Message";

    public static final String DIRECTORY_LOGGER_FILE = "i18n";

    public static final String DOT = ".";

    public static final String UNDER_LINE = "_";



    protected static String getResourceBundleName() {
        final StringBuilder builder = new StringBuilder();
        builder.append(DIRECTORY_LOGGER_FILE).append(DOT).append(PREFIX_LOGGER_FILE);
        return builder.toString();
    }
    
    protected static ResourceBundle getResourceBundle() {
    	return ResourceBundle.getBundle(getResourceBundleName());
    }
    protected static ResourceBundle getResourceBundle(Locale locale) {
    	return ResourceBundle.getBundle(getResourceBundleName(), locale);
    }

}

二、定義異常攔截器


/**
 * 異常攔截器,Service介面全域性異常處理
 *
 */
public class ServiceExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(ServiceExceptionHandler.class);
    
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object retVal = null;
        try{
            retVal = joinPoint.proceed(joinPoint.getArgs());
        } catch(Exception e){
            retVal = exceptionProcess(joinPoint, e);
        }
        return retVal;      
    }
    
    
	private Object exceptionProcess(ProceedingJoinPoint joinPoint, Exception e) {
		if (joinPoint.getArgs() != null) {
			logger.error("arguments:{}", joinPoint.getArgs());
		}
		String errorCode = MessageCode.SYSTEM_EXCEPTION;
		if (e instanceof GauzeException){
			errorCode = ((GauzeException) e).getErrorCode();
		} else {
			logger.error("系統異常:", e);
		}

		MethodSignature method = (MethodSignature) joinPoint.getSignature();
		Class<?> returnType = method.getReturnType();
		Object result = null;
		
		if (IPageResult.class.isAssignableFrom(returnType)) {
			result = PageResult.getFailedPageResult(errorCode, e.getMessage());
		} else if (IResult.class.isAssignableFrom(returnType)) {
			result = Result.getFailedResult(errorCode, e.getMessage());
		} 
		return result;
	}
}

三、Spring配置

<bean id="exceptionInterceptor" class="com.xx.xx.xx.gauze.interceptor.ServiceExceptionHandler"/>
    <!-- 異常攔截器,處理業務及執行時異常,此配置需在事務配置之前 -->
    <aop:config >  
        <!-- 定義切點 -->  
        <aop:pointcut id="serviceAspect" expression="execution(public * com.xx.xx.saas.gauze.service.impl.*ServiceImpl.*(..))"/>  
        <aop:aspect ref="exceptionInterceptor">
            <!-- 環繞通知 -->  
            <aop:around pointcut-ref="serviceAspect" method="around"/>
        </aop:aspect>  
    </aop:config>

四、異常code及message資原始檔

Message_zh_CN.properties檔案裡統一定義code及message