Browse Source

修改异常处理,采用RESTful API风格

sunyj 9 years ago
parent
commit
eea630cff6

+ 104 - 0
search-console/src/main/java/com/uas/search/console/core/advice/ExceptionHandlerAdvice.java

@@ -0,0 +1,104 @@
+/*CopyRright (c)2014: <www.usoftchina.com>
+ */
+package com.uas.search.console.core.advice;
+
+import java.sql.SQLRecoverableException;
+
+import org.apache.log4j.Logger;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.ui.ModelMap;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+
+import com.uas.search.console.core.exception.SystemError;
+
+/**
+ * <p>
+ * 基于Application的异常处理,以AOP的形式注册到SpringMVC的处理链
+ * </p>
+ * <p>
+ * 正常的业务流程,只需抛出对应的异常和相关的信息
+ * </P>
+ * <p>
+ * 不同的错误,对应不同的方法来处理
+ * </p>
+ * <p>
+ * 可以用不同的HttpStatus来表示具体的异常类型
+ * </p>
+ * <p>
+ * 客户端可以基于对应的HttpStatus Code做出最有利于自己的处理
+ * </p>
+ * 
+ * @author yingp
+ * 
+ */
+@ControllerAdvice
+public class ExceptionHandlerAdvice {
+
+	private final static Logger logger = Logger.getLogger(ExceptionHandlerAdvice.class);
+
+	/**
+	 * 处理运行时抛出异常
+	 * 
+	 * @param ex
+	 * @return
+	 */
+	@ExceptionHandler(RuntimeException.class)
+	public ResponseEntity<String> handleUnexpectedServerError(RuntimeException ex) {
+		logger.error("RuntimeException", ex);
+		HttpHeaders headers = new HttpHeaders();
+		headers.add("Content-Type", "application/text; charset=utf-8");
+		ex.printStackTrace();
+		return new ResponseEntity<String>("\u7CFB\u7EDF\u9519\u8BEF", headers, HttpStatus.INTERNAL_SERVER_ERROR);
+	}
+
+	/**
+	 * 处理连接池的连接失效抛出异常
+	 * 
+	 * @see SQLRecoverableException
+	 * @param ex
+	 * @return
+	 */
+	@ExceptionHandler(SQLRecoverableException.class)
+	public ResponseEntity<String> handleSQLRecoverableException(SQLRecoverableException ex) {
+		logger.error("SQLRecoverableException", ex);
+		HttpHeaders headers = new HttpHeaders();
+		headers.add("Content-Type", "application/text; charset=utf-8");
+		return new ResponseEntity<String>("\u7CFB\u7EDF\u9519\u8BEF", headers, HttpStatus.INTERNAL_SERVER_ERROR);
+	}
+
+	/**
+	 * 处理参数错误抛出异常
+	 * 
+	 * @see IllegalArgumentException
+	 * @param ex
+	 * @return
+	 */
+	@ExceptionHandler(IllegalArgumentException.class)
+	public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
+		logger.error("IllegalArgumentException", ex);
+		HttpHeaders headers = new HttpHeaders();
+		headers.add("Content-Type", "application/text; charset=utf-8");
+		return new ResponseEntity<String>("\u53C2\u6570\u9519\u8BEF", headers, HttpStatus.INTERNAL_SERVER_ERROR);
+	}
+
+	/**
+	 * 处理已捕获异常,明确传达给客户端错误码、错误信息
+	 * 
+	 * @see SystemError
+	 * @param ex
+	 * @return
+	 */
+	@ExceptionHandler(SystemError.class)
+	public ResponseEntity<ModelMap> handleSystemError(SystemError ex) {
+		HttpHeaders headers = new HttpHeaders();
+		headers.add("Content-Type", "application/json; charset=utf-8");
+		ModelMap map = new ModelMap();
+		map.put("success", false);
+		map.put("message", ex.getMessage());
+		return new ResponseEntity<ModelMap>(map, headers, HttpStatus.BAD_REQUEST);
+	}
+
+}

+ 30 - 0
search-console/src/main/java/com/uas/search/console/core/exception/SystemError.java

@@ -0,0 +1,30 @@
+package com.uas.search.console.core.exception;
+
+/**
+ * 需要把失败原因以成功的请求返回给客户端
+ * 
+ * @author suntg
+ * @since 2016年8月30日上午9:36:10
+ */
+public class SystemError extends RuntimeException {
+
+	/**
+	 * 序列号
+	 */
+	private static final long serialVersionUID = 1L;
+
+	private String message;
+
+	public String getMessage() {
+		return message;
+	}
+
+	public void setMessage(String message) {
+		this.message = message;
+	}
+
+	public SystemError(String message) {
+		this.message = message;
+	}
+
+}

+ 90 - 32
search-console/src/main/java/com/uas/search/console/service/impl/SearchServiceImpl.java

@@ -10,6 +10,7 @@ import java.util.Map;
 import java.util.Set;
 
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.log4j.Logger;
 import org.apache.lucene.analysis.Analyzer;
 import org.apache.lucene.analysis.TokenStream;
 import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
@@ -27,6 +28,7 @@ import org.springframework.util.StringUtils;
 import org.wltea.analyzer.lucene.IKAnalyzer;
 
 import com.alibaba.fastjson.JSONObject;
+import com.uas.search.console.core.exception.SystemError;
 import com.uas.search.console.core.util.FastjsonUtils;
 import com.uas.search.console.support.IndexSearcherManager;
 import com.uas.search.console.util.SearchConstants;
@@ -54,15 +56,22 @@ public class SearchServiceImpl implements SearchService {
 
 	private static IndexSearcherManager searcherManager = new IndexSearcherManager();
 
+	private static Logger logger = Logger.getLogger(SearchServiceImpl.class);
+
 	@Override
 	public List<Long> getKindIds(String keyword) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("搜索关键词无效");
+			message = "搜索关键词无效" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<Long> ids = new ArrayList<Long>();
@@ -86,13 +95,18 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public List<Map<String, Object>> getKinds(String keyword) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("搜索关键词无效");
+			message = "搜索关键词无效" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<Map<String, Object>> kinds = new ArrayList<Map<String, Object>>();
@@ -117,13 +131,18 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public List<Long> getBrandIds(String keyword) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("搜索关键词无效");
+			message = "搜索关键词无效" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<Long> ids = new ArrayList<Long>();
@@ -151,13 +170,18 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public List<Map<String, Object>> getBrands(String keyword) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("搜索关键词无效");
+			message = "搜索关键词无效" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<Map<String, Object>> brands = new ArrayList<Map<String, Object>>();
@@ -187,10 +211,13 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public Map<String, Object> getComponentIds(String keyword, PageParams page) {
+		String message = "";
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		if (page == null) {
@@ -275,13 +302,18 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public Set<Long> getKindIdsBySearchComponent(String keyword, String brandId) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("搜索关键词无效");
+			message = "搜索关键词无效" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		Set<Long> kindIds = new HashSet<Long>();
@@ -327,10 +359,13 @@ public class SearchServiceImpl implements SearchService {
 			return kinds;
 		}
 
+		String message = "";
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		BooleanQuery booleanQuery = new BooleanQuery();
@@ -359,13 +394,18 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public Set<Long> getBrandIdsBySearchComponent(String keyword, String kindId) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("搜索关键词无效");
+			message = "搜索关键词无效" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		Set<Long> brandIds = new HashSet<Long>();
@@ -410,11 +450,14 @@ public class SearchServiceImpl implements SearchService {
 		if (CollectionUtils.isEmpty(brandIds)) {
 			return brands;
 		}
-		searcherManager.maybeReopen();
 
+		String message = "";
+		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		BooleanQuery booleanQuery = new BooleanQuery();
@@ -481,22 +524,27 @@ public class SearchServiceImpl implements SearchService {
 
 	@Override
 	public List<Map<String, Object>> getSimilarComponents(String componentCode) {
+		String message = "";
 		if (isKeywordInvalid(componentCode)) {
-			throw new IllegalArgumentException("输入无效");
+			message = "输入无效:" + componentCode;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
-		IndexSearcher indexSearcher = searcherManager.get();
-		if (indexSearcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+		IndexSearcher searcher = searcherManager.get();
+		if (searcher == null) {
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<Map<String, Object>> result = new ArrayList<>();
 		try {
 			BooleanQuery booleanQuery = getBooleanQuery(SearchConstants.COMPONENT_CODE_FIELD, componentCode);
-			TopDocs hits = indexSearcher.search(booleanQuery, SIMILAR_NUM);
+			TopDocs hits = searcher.search(booleanQuery, SIMILAR_NUM);
 			ScoreDoc[] scoreDocs = hits.scoreDocs;
 			for (ScoreDoc scoreDoc : scoreDocs) {
-				Document document = indexSearcher.doc(scoreDoc.doc);
+				Document document = searcher.doc(scoreDoc.doc);
 				Map<String, Object> map = new HashMap<>();
 				map.put("id", Long.parseLong(document.get(SearchConstants.COMPONENT_ID_FIELD)));
 				map.put("code", document.get(SearchConstants.COMPONENT_CODE_FIELD));
@@ -505,20 +553,25 @@ public class SearchServiceImpl implements SearchService {
 		} catch (IOException e) {
 			e.printStackTrace();
 		} finally {
-			searcherManager.release(indexSearcher);
+			searcherManager.release(searcher);
 		}
 		return result;
 	}
 
 	@Override
 	public List<Map<String, Object>> getSimilarBrands(String brandName) {
+		String message = "";
 		if (isKeywordInvalid(brandName)) {
-			throw new IllegalArgumentException("输入无效");
+			message = "输入无效:" + brandName;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
 		IndexSearcher searcher = searcherManager.get();
 		if (searcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<Map<String, Object>> brands = new ArrayList<Map<String, Object>>();
@@ -617,30 +670,35 @@ public class SearchServiceImpl implements SearchService {
 	 * @return
 	 */
 	private List<String> getSimilarValues(String field, String keyword) {
+		String message = "";
 		if (isKeywordInvalid(keyword)) {
-			throw new IllegalArgumentException("输入无效");
+			message = "输入无效:" + keyword;
+			logger.error(message);
+			throw new SystemError(message);
 		}
 		searcherManager.maybeReopen();
-		IndexSearcher indexSearcher = searcherManager.get();
-		if (indexSearcher == null) {
-			throw new RuntimeException("获取索引文件失败");
+		IndexSearcher searcher = searcherManager.get();
+		if (searcher == null) {
+			message = "获取索引文件失败";
+			logger.error(message);
+			throw new SystemError(message);
 		}
 
 		List<String> result = new ArrayList<>();
 		try {
 			BooleanQuery booleanQuery = getBooleanQuery(field, keyword);
-			TopDocs hits = indexSearcher.search(booleanQuery, SIMILAR_NUM);
+			TopDocs hits = searcher.search(booleanQuery, SIMILAR_NUM);
 			ScoreDoc[] scoreDocs = hits.scoreDocs;
 			for (ScoreDoc scoreDoc : scoreDocs) {
 				Set<String> fieldsToLoad = new HashSet<>();
 				fieldsToLoad.add(field);
-				Document document = indexSearcher.doc(scoreDoc.doc, fieldsToLoad);
+				Document document = searcher.doc(scoreDoc.doc, fieldsToLoad);
 				result.add(document.get(field));
 			}
 		} catch (IOException e) {
 			e.printStackTrace();
 		} finally {
-			searcherManager.release(indexSearcher);
+			searcherManager.release(searcher);
 		}
 		return result;
 	}