一种系统异常设计思路

1  系统只有一个异常基类继承RuntimeEcption,如果仅仅依靠异常子类的种类来区分,很容易造成类爆炸。
2  设置错误code,用枚举来保存,这样来区分异常类别,而且非常方便进行处理和国际化。
3  增加异常时参数设置,debug很容易找到当时的环境。
4  重写异常方法,抛出异常时打印出code和环境参数
5  正确包装其他异常,不用默认构造函数包装,防止异常无意义的嵌套。
package com.northconcepts.exception;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;

public class SystemException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public static SystemException wrap(Throwable exception, ErrorCode errorCode) {
        if (exception instanceof SystemException) {
            SystemException se = (SystemException)exception;
        	if (errorCode != null && errorCode != se.getErrorCode()) {
                return new SystemException(exception.getMessage(), exception, errorCode);
			}
			return se;
        } else {
            return new SystemException(exception.getMessage(), exception, errorCode);
        }
    }
    
    public static SystemException wrap(Throwable exception) {
    	return wrap(exception, null);
    }
    
    private ErrorCode errorCode;
    private final Map<String,Object> properties = new TreeMap<String,Object>();
    
    public SystemException(ErrorCode errorCode) {
		this.errorCode = errorCode;
	}

	public SystemException(String message, ErrorCode errorCode) {
		super(message);
		this.errorCode = errorCode;
	}

	public SystemException(Throwable cause, ErrorCode errorCode) {
		super(cause);
		this.errorCode = errorCode;
	}

	public SystemException(String message, Throwable cause, ErrorCode errorCode) {
		super(message, cause);
		this.errorCode = errorCode;
	}
	
	public ErrorCode getErrorCode() {
        return errorCode;
    }
	
	public SystemException setErrorCode(ErrorCode errorCode) {
        this.errorCode = errorCode;
        return this;
    }
	
	public Map<String, Object> getProperties() {
		return properties;
	}
	
    @SuppressWarnings("unchecked")
	public <T> T get(String name) {
        return (T)properties.get(name);
    }
	
    public SystemException set(String name, Object value) {
        properties.put(name, value);
        return this;
    }
    
    //重写Runtime方法。这里打印虚拟机错误信息,注意PrintStream要同步,不然异常并非时会乱掉
    public void printStackTrace(PrintStream s) {
        synchronized (s) {
            printStackTrace(new PrintWriter(s));
        }
    }
    //把出异常时的参数也 打印出来,方便调试
    public void printStackTrace(PrintWriter s) { 
        synchronized (s) {
            s.println(this);
            s.println("\t-------------------------------");
            if (errorCode != null) {
	        	s.println("\t" + errorCode + ":" + errorCode.getClass().getName()); 
			}
            for (String key : properties.keySet()) {
            	s.println("\t" + key + "=[" + properties.get(key) + "]"); 
            }
            s.println("\t-------------------------------");
            StackTraceElement[] trace = getStackTrace();
            for (int i=0; i < trace.length; i++)
                s.println("\tat " + trace[i]);

            Throwable ourCause = getCause();
            if (ourCause != null) {
                ourCause.printStackTrace(s);
            }
            s.flush();
        }
    }
    
}

public class SystemExceptionExample2 {

	private static final int MIN_LENGTH = 10;

	public static void main(String[] args) {
		validate("email", "abc");
	}

	public static void validate(String field, String value) {
		if (value == null || value.length() < MIN_LENGTH) {
			throw new SystemException("发生错误!",ValidationCode.VALUE_TOO_SHORT)
			.set("field", field).set("value", value).set("min-length", MIN_LENGTH); 
		}
	}

}

  public static void main(String[] args) {
        System.out.println(getUserText(ValidationCode.VALUE_TOO_SHORT));
    }
    
    public static String getUserText(ErrorCode errorCode) {
        if (errorCode == null) {
            return null;
        }
        String key = errorCode.getClass().getSimpleName() + "__" + errorCode;
        ResourceBundle bundle = ResourceBundle.getBundle("com.northconcepts.exception.example.exceptions");
        return bundle.getString(key);
    }

包装异常
catch (IOException e) {
            throw SystemException.wrap(e,PaymentCode.CREDIT_CARD_EXPIRED).set("fileName", "aaa");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值