统一异常管理

一、自定义异常处理器


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值