java中异常的处理

本文参考了:http://blog.csdn.net/gaojava/article/details/8575683
在异常处理时,通过设置错误code,用枚举来保存,来区分异常类别,也方便进行处理和后期的国际化。参考前人的成果,初步实现了异常处理功能,代码如下:定义枚举类的接口,该接口主要用来进行错误Code的处理

</pre><pre name="code" class="java">package Exception;
public interface ErrorCode {
	 public int getNumber();
}



定义枚举类,用来分类各种异常,
package Exception;

public enum ValidationCode implements ErrorCode {
	VALUE_REQUIRED(201),
	INVALID_FORMAT(202),
	VALUE_TOO_SHORT(203),
	VALUE_TOO_LONGS(204);
	
	private final int number;
	 
	  private ValidationCode(int number) {
	    this.number = number;
	  }
	@Override
	public int getNumber() {
		// TODO Auto-generated method stub
		return this.number;
	}

}

package Exception;

public enum PaymentCode implements ErrorCode {

	
	  SERVICE_TIMEOUT(101),
	  CREDIT_CARD_EXPIRED(102),
	  AMOUNT_TOO_HIGH(103),
	  INSUFFICIENT_FUNDS(104);<pre name="code" class="java">
private final int number; private PaymentCode(int number) { this.number = number; } @Override public int getNumber() { return number; } }
 构建异常基类 

package 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;
    private ErrorCode errorCode;
    //加入Map主要是为了记录为异常添加的其他属性信息
    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 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);
    }
    
   
    
  
	
	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();
        }
    }
    
}

测试异常:

package Exception;

import java.util.ResourceBundle;

public class SystemExceptionExample2 {
	 private static final int MIN_LENGTH = 10;  
	  
	    public static void main(String[] args) {  
	        validate("email", "abc");  
	    	//System.out.println(getUserText(ValidationCode.VALUE_TOO_SHORT)); 
	    }  
	  
	    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);   
	        }  
	    }  
}

下面主要通过ResourceBundle进行异常信息的多种显示,这里只是做了初步的尝试


添加异常处理信息的资源类

package Exception;

import java.util.ListResourceBundle;

public class MyResource extends ListResourceBundle{

	public Object[][] getContents() { 
		return contents;
		} 
	static final Object[][] contents = {
		
		{"ValidationCode__VALUE_REQUIRED", "缺少必要值"}, {"ValidationCode__INVALID_FORMAT", "格式不对"},{"ValidationCode__VALUE_TOO_SHORT", "值太短"},{"ValidationCode__VALUE_TOO_LONGS", "值太长"},
		
	};
	
}


测试:

package Exception;

import java.util.ResourceBundle;

public class SystemExceptionExample2 {
	 private static final int MIN_LENGTH = 10;  
	  
	    public static void main(String[] args) {  
	        //validate("email", "abc");  
	    	System.out.println(getUserText(ValidationCode.VALUE_TOO_SHORT)); 
	    }  
	  
	    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 String getUserText(ErrorCode errorCode) {  
	        if (errorCode == null) {  
	            return null;  
	        }  
	        String key = errorCode.getClass().getSimpleName() + "__" + errorCode;  
	        ResourceBundle bundle = ResourceBundle.getBundle("Exception.MyResource");  
	        return bundle.getString(key);  
	    }  

}


以上有什么错误和不对的地方,请大神指教!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值