---
title: "struts处理自定义异常"
author: "g21121"
date: "2012-03-08T16:35:05Z"
tags: []
categories: ["企业架构"]
slug: "struts"
draft: false
lastmod: "2012-03-08T16:35:05Z"
id: 1446642
url: "https://286.iteye.com/blog/1446642"
---

很多时候我们会用到自定义异常来表示特定的错误情况，自定义异常比较简单，只要分清是运行时异常还是非运行时异常即可，运行时异常不需要捕获，继承自RuntimeException，是由容器自己抛出，例如空指针异常。

非运行时异常继承自Exception，在抛出后需要捕获，例如文件未找到异常。

此处我们用的是非运行时异常，首先定义一个异常LoginException:

```
/**
 * 类描述：登录相关异常
 * 
 * @author ming.li <a href="http://g21121.iteye.com">iteye blog</a>
 * @time 2011-4-27 下午01:08:11
 */
public class LoginException extends Exception {

	/** 版本号 */
	private static final long serialVersionUID = 5843727837651089745L;
	/** 错误码 */
	private String messageKey;
	/** 参数 */
	private Object[] params;

	/**
	 * 默认构造函数
	 */
	public LoginException() {
		super();
	}

	/**
	 * 登录相关异常，页面直接显示错误信息<br/>
	 * 
	 * @param messageKey
	 *            错误码
	 * @param params
	 *            参数
	 */
	public LoginException(String messageKey, Object... params) {
		this.messageKey = messageKey;
		this.params = params;
	}

	/**
	 * @return the messageKey
	 */
	public String getMessageKey() {
		return messageKey;
	}

	/**
	 * @return the params
	 */
	public Object[] getParams() {
		return params;
	}

}
```

这是个登录异常，用来表示登录情况下发生的各种错误。这个异常只有基本内容，可以根据你的情况自行添加。

 

在发生登录错误时调用代码：

```
public String login() throws LoginException {
    throw new LoginException("9999");// 用户名或密码错误
}
```

其中的9999是错误码，这个可以自己定义，用来在国际化时显示不同信息。

此时抛出了一个登录异常的信息，我们就需要在跳转是捕获并显示在页面中。

首先在struts的action配置中捕获此异常：

```
<package name="login-default" namespace="/" extends="struts-default">

<!-- 登录 -->
<action name="login" class="loginAction" method="login">
	<exception-mapping result="login" exception="com.xxx.exception.LoginException"/>
	<result name="success">index.jsp</result>
	<result name="login">login.jsp</result>
</action>
</package>
```

 此时我们可以看到，当抛出LoginException时struts会捕获并跳转到login这个result上，进而跳转到login.jsp。

在login.jsp中我们就需要去显示异常信息：

```
<%@taglib prefix="s" uri="/struts-tags"%>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<!-- 异常信息显示 -->
<c:if test="${!empty exception}"><s:property value="%{getText(exception.messageKey)}"/></c:if>
```

 这样异常信息就会被显示了。