设计的一个自定义异常的封装

package com.d1xn.core.exception;

/**
 * 异常枚举
 * 
 * @author gonghf
 * @version 1.0 Jan 5, 2009
 */
public final class D1xnErrorEnum {

	public final static D1xnError E1000 = new D1xnError("1000", "没有该异常");
	public final static D1xnError E2000 = new D1xnError("2000", "数据库连接出错");

	final static D1xnError getError(String errorCode) {
		try {
			return (D1xnError) new D1xnErrorEnum().getClass().getDeclaredField(
					"E" + errorCode).get(new D1xnErrorEnum());

		} catch (Exception e) {
			throw new D1xnRuntimeException(D1xnErrorEnum.E1000);
		}

	}

	final static class D1xnError {

		private static final long serialVersionUID = 217246126247731875L;

		private String code;
		private String message;
		private D1xnError(String code, String msg) {
			this.message="d1xn-" + code + ":" + msg;
		}

		public final String getCode() {
			return this.code;
		}
		
		public final String getMessage() {
			return this.message;
		}
		
	}

}

  package com.d1xn.core.exception;

/**
 * D1XN异常
 * 
 * @author gonghf
 * @version 1.0 Jan 5, 2009
 */
public final class D1xnException extends Exception {

	private static final long serialVersionUID = 1387623981549785491L;
	private String code;

	public D1xnException(D1xnErrorEnum.D1xnError error) {
		super(error.getMessage());
		this.code=error.getCode();
	}

	public D1xnException(String errorCode) {
		super(D1xnErrorEnum.getError(errorCode).getMessage());
		this.code=errorCode;

	}

	public final String getCode() {
		return this.code;
	}
}

 package com.d1xn.core.exception;

/**
 * D1XN运行时异常
 * 
 * @author gonghf
 * @version 1.0 Jan 5, 2009
 */
public final class D1xnRuntimeException extends RuntimeException {

	private static final long serialVersionUID = 2325188130006865682L;
	private String code;
	public D1xnRuntimeException(D1xnErrorEnum.D1xnError error) {
		super(error.getMessage());
		this.code=error.getCode();
	}

	public D1xnRuntimeException(String errorCode) {
		super(D1xnErrorEnum.getError(errorCode).getMessage());
		this.code=errorCode;
	}

	public final String getCode() {
		return this.code;
	}
}

 

你可能感兴趣的:(自定义异常)