论坛首页 Java企业应用论坛

Spring定制自己的异常

浏览 2225 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-10-12  

为了能根据不同的情况做出不同的反应,我们可以让不同的情况抛出异常。

Spring里提供了HandlerExceptionResolver类来捕获异常。

下面 以代码作说明

1.首先抛出异常

if (meeting.getNeedExpert().size() == 0
					|| meeting.getProject().size() == 0) {
				throw new NoExpertException("此会议还没有专家");
			}

 我们自己定义了一个异常类为NoExpertException。

public class NoExpertException extends IllegalStateException {
  
	
	private static final long serialVersionUID = 0L;

	public NoExpertException() {
    }

    public NoExpertException(String s) {
        super(s);
    }
}

 2.配置异常解析器

	<bean id="noExpertExceptionResolver"
		class="com.itware.lxgl.workflow.exception.NoExpertExceptionResolver">
		<property name="order">
			<value>1</value>
		</property>
		<property name="exceptionView">
			<value>exception/noExpertException</value>
		</property>
		<property name="backUrl">
			<value>/home/todoList.htm</value>
		</property>
		<property name="backMsgKey">
			<value>返回</value>
		</property>
	</bean>

 3.编写解析器代码

public class NoExpertExceptionResolver implements Ordered,
        HandlerExceptionResolver {
	private int order;
    private String exceptionView;

    private String backUrl = "/";

    private String backMsgKey;

    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof NoExpertException) {
        	String errorMessage = ex.getMessage();
            Map model = new HashMap();
            model.put("backUrl", backUrl);
            model.put("backMsgKey", backMsgKey);
            model.put("errorMessage", errorMessage);
            return new ModelAndView(exceptionView, model);
        }

        return null;
    }

    public int getOrder() {
        return 0;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public void setExceptionView(String exceptionView) {
        this.exceptionView = exceptionView;
    }

    public void setBackUrl(String backUrl) {
        this.backUrl = backUrl;
    }

    public void setBackMsgKey(String backMsgKey) {
        this.backMsgKey = backMsgKey;
    }
}

 继承HandlerExceptionResolver以捕获异常,进行处理。!

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics