当前位置: 移动技术网 > IT编程>开发语言>Java > Jersey框架的统一异常处理机制分析

Jersey框架的统一异常处理机制分析

2019年07月22日  | 移动技术网IT编程  | 我要评论

一、背景

写这边文章源于有朋友问过java中的checked exception和unchecked exception有啥区别,当时我对其的回答是:我编程时仅用runtimeexception。其实,我说句话我是有前提的,确切的应该这么说:在成熟的开发框架下编写业务代码,我只使用或关注runtimeexception。因为,由于框架往往将异常的处理统一封装,这样以便程序员更好的关注业务代码,而业务的一些错误通常是在系统运行期间发生的,因此业务的异常通常被设计为runtimeexception的子类。

我的回答显然不能让朋友满意!因为,不管是任何一个初学java的都知道,在我们学习io类和jdbc编程的时候,我们用了大量的try...catch...,这种反复重复的try...catch会让我们对java的异常记忆深刻!初学者往往不清楚java的异常为什么会设计成这个样子,他们通常会对异常只进行简单的处理——在catch块里面简单的把异常打印出来,用的最多的就是这个语句:

e.printstacktrace()。 

我们还与一些记忆,比如数组越界这类的异常:

java.lang.arrayindexoutofboundsexception: 6

这也会使我们记忆犹新,因为在我们调试程序的时候,它经常出现!我们会发现这类异常并不需要在代码里用try...catch...去捕获它。

上面两个例子,其实就是朋友问到的checked exception和unchecked exception,需要try...catch...的异常是checked exception,不需要的则是unchecked exception。如果要说他们的区别,我说他们一个要try...catch...,一个不需要,这样的回答行吗?我认为这样的回答是苍白的。有同学会进一步说,try...catch很显然,是强制要求抛出异常的方法调用者显式的处理异常,那e.printstacktrace()算不算处理了异常,我认为那只算是一种简单懒惰的处理方式吧!那什么样的处理方式算是高明的,java语言设计者其实是期望发生异常后,调用者能够在catch里将异常恢复回来,使得程序能够继续执行下去。但是,“聪明的程序员都是懒惰的”呵呵,大多数情况下我们选择异常出现后只进行记录日志和ui用户提示,后面我会结合jersey框架,说说其中的统一异常处理。读到这里,有人会说,那checked exception和unchecked exception异常的区别就是,一个需要处理,一个不需要处理。这个回答正确吗?我认为是错误的!我的观点是:无论是checked exception还是unchecked exception,我们都要进行处理!

上一段,我们似乎还是没有解决checked exception和unchecked exception的区别,我认为如何给出答案并不重要,重要的是我们怎么去处理这些异常,以及我们如何在开发时使用异常。

我的观点是(web系统开发):

1、在框架层面封装checked exception,将其转化为unchecked exception,避免开发过程中编写繁冗的try...catch代码。
2、业务层面的开发,根据程序代码职责定义不同的runtimeexception(它就是unchecked exception,一般定义为runtimeexception的子类)
3、通过前两个观点,系统中自定义的异常将只存在unchecked exception,系统只在于客户端交换数据的上层,设置统一异常处理机制,并将一些异常转化为用户所能理解的信息传达给用户。
4、其他如业务层,数据持久层,等底层只负责将异常抛出即可,但要注意不要丢失掉异常堆栈(这一点是初学者容易犯的一个错误)。

背景说的够长了!让我们进入正题吧,看看jersey框架的统一异常处理器是怎样使用的!

二、jersey框架的统一异常处理机制

有如下约定:

1、示例采用jersey1.x版本
2、spring版本为2.5
3、为了简单起见,示例项目不采用maven机制

示例的业务场景说明:

1、我们通过读取一个properties配置文件,配置文件的内容为:

key1=hello 
key2=iteye.com

2、发起一个http://www.lhsxpumps.com/_localhost:8888/a/resources/test?n=11的get请求,要求n为数字,且必须小于10,如果n错误,将产生一个unchecked exception错误。

3、本示例中数据访问层将读取一个文件,读取文件错误将会产生checked exception错误。

示例项目结构设计

代码片段说明

1、数据存储文件:test.properties

key1=hello 
key2=iteye.com 

这就是我们要读取的文件,为了简单起见,它是一个properties文件。

2、数据访问类:testdao.java

package com.iteye.redhacker.jersey.dao;

import java.io.ioexception;
import java.io.inputstream;
import java.net.url;
import java.util.properties;

import org.springframework.stereotype.component;

import com.iteye.redhacker.jersey.exception.daoexception;
import com.iteye.redhacker.jersey.exception.exceptioncode;

@component
public class testdao {
	public string sayhello() {
		classloader classloader = testdao.class.getclassloader();
		string inifile = "com/iteye/redhacker/jersey/dao/test.properties";
		url url = classloader.getresource(inifile);
		inputstream is;
		try {
			is = url.openstream();
		} catch (ioexception e) {
			throw new daoexception(e, exceptioncode.read_file_failed);
		}
		properties proper = null;
		try {
			if (proper == null) {
				proper = new properties();
			}
			proper.load(url.openstream());
		} catch (ioexception e) {
			throw new daoexception(e, exceptioncode.read_config_failed);
		} finally {
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (ioexception e) {
					throw new daoexception(e, exceptioncode.colse_file_failed);
				}
			}
		}
		return proper.getproperty("key1") + "," + proper.getproperty("key2");
	}
}

在该类中,将checked exception全部转化为unchecked exception(我们自定义的exception),调用sayhello()方法时,不再需要try...catch...

3、业务实现类:testservice.java

package com.iteye.redhacker.jersey.service;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;

import com.iteye.redhacker.jersey.dao.testdao;
import com.iteye.redhacker.jersey.exception.exceptioncode;
import com.iteye.redhacker.jersey.exception.serviceexception;

@component

public class testservice {
	
	@autowired
	private testdao testdao;
	
	public string sayhello(int n) {
		// 业务上规定n不能大于10 
		if (n > 10) {
			throw new serviceexception(exceptioncode.must_be_less_than_10);
		}
		return testdao.sayhello();
	}

	/**
	 * @param testdao the testdao to set
	 */
	public void settestdao(testdao testdao) {
		this.testdao = testdao;
	}
}

在该类中,我们抛出了一个自己的业务异常,它是一个unchecked exception。

注意:我们使用@autowired注入了testdao类,@autowired是spring提供的一个注解;我们必须提供一个要注解属性的set方法,否则注解将失败。

4、请求接入类:testresources.java

package com.iteye.redhacker.jersey.delegate;

import javax.ws.rs.get;
import javax.ws.rs.path;
import javax.ws.rs.produces;
import javax.ws.rs.queryparam;
import javax.ws.rs.core.mediatype;

import com.iteye.redhacker.jersey.service.testservice;
import com.sun.jersey.api.spring.autowire;

@path("/test")
@autowire
public class testresources {
	
	private testservice testservice;
	
	@get
	@produces(mediatype.text_plain)
	public string sayhello(@queryparam("n") int n) {
		return testservice.sayhello(n);
	}

	/**
	 * @param testservice the testservice to set
	 */
	public void settestservice(testservice testservice) {
		this.testservice = testservice;
	}
	
	
}

这里是jersey定义的一个资源,我们可以这样访问这个资源:发起get请求,访问uri为/resources/test,可以传递一个查询参数n,例如:/resources/test?n=1

注意:我们使用了@autowire并不是spring的一个注解,它是jersey-srping集成包的一个注解;我们必须提供一个要注解属性的set方法,否则注解将失败。

5、统一异常处理器类:exceptionmappersupport.java

package com.iteye.redhacker.jersey.jaxrs;

import javax.servlet.servletcontext;
import javax.servlet.http.httpservletrequest;
import javax.ws.rs.core.context;
import javax.ws.rs.core.mediatype;
import javax.ws.rs.core.response;
import javax.ws.rs.core.response.status;
import javax.ws.rs.ext.exceptionmapper;
import javax.ws.rs.ext.provider;

import org.apache.log4j.logger;
import org.springframework.web.context.webapplicationcontext;

import com.iteye.redhacker.jersey.exception.baseexception;
import com.iteye.redhacker.jersey.exception.exceptioncode;
import com.sun.jersey.api.notfoundexception;

/**
 * 统一异常处理器
 */
@provider
public class exceptionmappersupport implements exceptionmapper<exception> {
	private static final logger logger = logger
			.getlogger(exceptionmappersupport.class);

	private static final string context_attribute = webapplicationcontext.root_web_application_context_attribute;

	@context
	private httpservletrequest request;

	@context
	private servletcontext servletcontext;

	/**
	 * 异常处理
	 * 
	 * @param exception
	 * @return 异常处理后的response对象
	 */
	public response toresponse(exception exception) {
		string message = exceptioncode.internal_server_error;
		status statuscode = status.internal_server_error;
		webapplicationcontext context = (webapplicationcontext) servletcontext
				.getattribute(context_attribute);
		// 处理unchecked exception
		if (exception instanceof baseexception) {
			baseexception baseexception = (baseexception) exception;
			string code = baseexception.getcode();
			object[] args = baseexception.getvalues();
			message = context.getmessage(code, args, exception.getmessage(),
					request.getlocale());

		} else if (exception instanceof notfoundexception) {
			message = exceptioncode.request_not_found;
			statuscode = status.not_found;
		} 
		// checked exception和unchecked exception均被记录在日志里
		logger.error(message, exception);
		return response.ok(message, mediatype.text_plain).status(statuscode)
				.build();
	}
}

在这个类里面我们处理了我们定义的unchecked exception异常,还处理了系统未知的exception(包括未知的unchecked exception和checked exception)。我们的处理方式是:a、记录异常日志;b、向客户端抛一个标准的http标准错误状态码和错误消息,由客户端对错误信息进行自行处理,值得说明的是,这种处理方式是rest所提倡的,它恰当的使用了http标准状态码;

在这个类中我们还使用了spring的国际化配置组件,用于对系统抛出的错误key进行国际化转换,这有利于我们的项目国际化升级。

6、自定义异常基类:baseexception.java

package com.iteye.redhacker.jersey.exception;

/**
 * 异常基类,各个模块的运行期异常均继承与该类
 */
public class baseexception extends runtimeexception {

  /**
   * the serialversionuid
   */
  private static final long serialversionuid = 1381325479896057076l;

  /**
   * message key
   */
  private string code;

  /**
   * message params
   */
  private object[] values;

  /**
   * @return the code
   */
  public string getcode() {
    return code;
  }

  /**
   * @param code the code to set
   */
  public void setcode(string code) {
    this.code = code;
  }

  /**
   * @return the values
   */
  public object[] getvalues() {
    return values;
  }

  /**
   * @param values the values to set
   */
  public void setvalues(object[] values) {
    this.values = values;
  }

  public baseexception(string message, throwable cause, string code, object[] values) {
    super(message, cause);
    this.code = code;
    this.values = values;
  }
}

这个类定义了项目异常类的基本模板,其他异常继承与它。值得注意的是,它巧妙的利用了国际化配置的一些特征,甚至可以抛出下面这样定义的一个错误消息,通过传递参数的方式,复用错误信息:

第{0}个{1}参数错误

7、其他异常基本差不多,只是类型不同,我们看一下daoexception.java

package com.iteye.redhacker.jersey.exception;

public class daoexception extends baseexception {

	/**
	 * constructors
	 * 
	 * @param code
	 *      错误代码
	 */
	public daoexception(string code) {
		super(code, null, code, null);
	}

	/**
	 * constructors
	 * 
	 * @param cause
	 *      异常接口
	 * @param code
	 *      错误代码
	 */
	public daoexception(throwable cause, string code) {
		super(code, cause, code, null);
	}

	/**
	 * constructors
	 * 
	 * @param code
	 *      错误代码
	 * @param values
	 *      一组异常信息待定参数
	 */
	public daoexception(string code, object[] values) {
		super(code, null, code, values);
	}

	/**
	 * constructors
	 * 
	 * @param cause
	 *      异常接口
	 * @param code
	 *      错误代码
	 * @param values
	 *      一组异常信息待定参数
	 */
	public daoexception(throwable cause, string code, object[] values) {
		super(code, null, code, values);
	}

	private static final long serialversionuid = -3711290613973933714l;

}

它继承了baseexception,当抛出这个异常时,我们就从异常名字上直接初步判断出,错误出自dao层。

8、errmsg.properties用于定义异常信息,来看一下:

read.file.failed=读取文件失败
read.config.failed=读取配置项失败
must.be.less.than.10=参数必须小于10
colse.file.failed=关闭文件失败
request.not.found=没有找到相应的服务
internal.server.error=服务器内部错误

三、部署及测试

你可以在本文附件里下载到源码。导入eclipse后,查看源码。

部署很简单,只要将你的tomcat/config/server.xml里加入:

<host>
...
<context path="/a" reloadable="true" docbase="d:/workspace/test/jerseyexceptionmappertest/web" />

</host>

启动tomcat就可以了!

做两个测试:
1、

2、

第1个测试,还可以在log中看到如下异常错误:

[2013-08-15 00:25:55] [error] 参数必须小于10
com.iteye.redhacker.jersey.exception.serviceexception: must.be.less.than.10
	at com.iteye.redhacker.jersey.service.testservice.sayhello(testservice.java:20)
	at com.iteye.redhacker.jersey.delegate.testresources.sayhello(testresources.java:21)
	at sun.reflect.nativemethodaccessorimpl.invoke0(native method)
	at sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:39)
	at sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:25)
	at java.lang.reflect.method.invoke(method.java:597)
	at com.sun.jersey.spi.container.javamethodinvokerfactory$1.invoke(javamethodinvokerfactory.java:60)
	at com.sun.jersey.server.impl.model.method.dispatch.abstractresourcemethoddispatchprovider$typeoutinvoker._dispatch(abstractresourcemethoddispatchprovider.java:185)
	at com.sun.jersey.server.impl.model.method.dispatch.resourcejavamethoddispatcher.dispatch(resourcejavamethoddispatcher.java:75)
	at com.sun.jersey.server.impl.uri.rules.httpmethodrule.accept(httpmethodrule.java:288)
	at com.sun.jersey.server.impl.uri.rules.resourceclassrule.accept(resourceclassrule.java:108)
	at com.sun.jersey.server.impl.uri.rules.righthandpathrule.accept(righthandpathrule.java:147)
	at com.sun.jersey.server.impl.uri.rules.rootresourceclassesrule.accept(rootresourceclassesrule.java:84)
	at com.sun.jersey.server.impl.application.webapplicationimpl._handlerequest(webapplicationimpl.java:1483)
	at com.sun.jersey.server.impl.application.webapplicationimpl._handlerequest(webapplicationimpl.java:1414)
	at com.sun.jersey.server.impl.application.webapplicationimpl.handlerequest(webapplicationimpl.java:1363)
	at com.sun.jersey.server.impl.application.webapplicationimpl.handlerequest(webapplicationimpl.java:1353)

关于其他的一些测试,大家可以去尝试一下,比如故意把test.properties删除,当找不到要读取的文件时,checked exception是如何转化为我们自己定义个unchecked exception,并记录下了日志,返回给客户端标准的http错误状态码和错误信息。

四、总结

1、通过jersey框架我们不难看出,在web项目开发来讲,对于checked exception和unchecked exception的处理我们尽可能在框架层面就进行了统一处理,以便我们更加关注与业务的实现。

2、如果是非web项目,我想,程序架构设计者也应当尽量统一的处理异常;如果不做统一处理,当遇到checked exception,我们应当对其进行恰当的异常处理,而不是不是简单的做一个e.printstacktrace()的处理;如果我们不能恢复异常,那我们至少要将异常的错误信息完整的记录到日志文件中去,以便后续的程序出现故障时进行错误排查。

全文(完)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网