自定义封装Exception异常抛出

Posted 47gamer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义封装Exception异常抛出相关的知识,希望对你有一定的参考价值。

话不多说直接上代码,朋友们可自己测试用于项目:

BaseException类(基础类)

   /**
     *异常处理基类
     */
    public class BaseException extends RuntimeException {

        private static final long serialVersionUID = -3653870580234213024L;
        protected String messageKey;


        public BaseException() {
            super();
        }

        public BaseException(String s, Throwable throwable) {
            super(s, throwable);
        }

        public BaseException(Throwable throwable) {
            super(throwable);
        }

        public BaseException(String messageKey) {
            super();
            this.messageKey = messageKey;
        }


        /**
         * 取得异常信息key
         * @return String
         */
        public String getMessageKey() {
            return messageKey;
        }


        /**
         * 设置异常信息key
         * @param messageKey
         * @return void
         */
        public void setMessageKey(String messageKey) {
            this.messageKey = messageKey;
        }

        @Override
        public String getMessage() {
            return messageKey;
        }

 

DaoException类 (Dao层)

public class DaoException extends BaseException {

	private static final long serialVersionUID = -9006104640618533135L;

	public DaoException(String messageKey) {
		super.setMessageKey(messageKey);
	}

	public DaoException(String messageKey, Throwable t) {
		super.setMessageKey(messageKey);
		super.initCause(t);
	}

	public DaoException(Throwable t) {
		super.setMessageKey(t.getClass().getSimpleName());
		super.initCause(t);
	}

	public Throwable getOrignalException() {
		Throwable t = this.getCause();
		while(t.getCause() != null){
			t = t.getCause();
		}
		return t;
	}

	public String getOrignalMessageKey() {
		return this.getOrignalException().getClass().getSimpleName();
	}
}

 

ServiceException类(业务层)

public class ServiceException extends BaseException {

	private static final long serialVersionUID = -9006104640618533135L;

	public ServiceException(String messageKey) {
		super(messageKey);
	}

	public ServiceException(Throwable t) {
		if(t instanceof BaseException){
			super.setMessageKey(((BaseException) t).getMessageKey());
		}
		super.initCause(t);
	}

	public ServiceException(String messageKey, Throwable t) {
		super.setMessageKey(messageKey);
		super.initCause(t);
	}

	public ServiceException() {

	}

	public Throwable getOrignalException() {
		Throwable t = this.getCause();
		while(t.getCause() != null){
			t = t.getCause();
		}
		return t;
	}

	public String getOrignalMessageKey() {
		return this.getOrignalException().getClass().getSimpleName();
	}
}

 

以上是关于自定义封装Exception异常抛出的主要内容,如果未能解决你的问题,请参考以下文章

php 抛出一个异常throw new Exception(...),报错Class 'ss\Exception' not found为啥?

Throwable -抛出异常类与自定义异常类

java基础-异常

python异常触发及自定义异常类

Java_异常介绍

关于thinkphp5手动抛出Http异常时自定义404页面报错的问题