Просмотр исходного кода

增加异常处理,形成RestFul风格API

suntg 9 лет назад
Родитель
Сommit
1a75fca92e

+ 13 - 21
src/main/java/com/uas/report/controller/PrintController.java

@@ -13,11 +13,11 @@ import org.apache.commons.lang.ArrayUtils;
 import org.apache.log4j.Logger;
 import org.apache.log4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.stereotype.Controller;
-import org.springframework.util.CollectionUtils;
 import org.springframework.util.StringUtils;
 import org.springframework.util.StringUtils;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.ResponseBody;
 
 
+import com.uas.report.core.exception.SystemError;
 import com.uas.report.service.PrintService;
 import com.uas.report.service.PrintService;
 
 
 /**
 /**
@@ -54,8 +54,9 @@ public class PrintController {
 	 * @return
 	 * @return
 	 */
 	 */
 	@RequestMapping("/export")
 	@RequestMapping("/export")
-	public String export(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters,
-			String exportFileType, HttpServletRequest request, HttpServletResponse response) {
+	public String export(String userName, String reportName, String whereCondition,
+			Map<String, Object> otherParameters, String exportFileType, HttpServletRequest request,
+			HttpServletResponse response) {
 		String message = "";
 		String message = "";
 		if (StringUtils.isEmpty(userName)) {
 		if (StringUtils.isEmpty(userName)) {
 			message = "未传入当前账套用户名!";
 			message = "未传入当前账套用户名!";
@@ -138,35 +139,26 @@ public class PrintController {
 	@ResponseBody
 	@ResponseBody
 	public Map<String, Object> loadPdfData(String userName, String reportName, String whereCondition,
 	public Map<String, Object> loadPdfData(String userName, String reportName, String whereCondition,
 			Map<String, Object> otherParameters, Integer pageIndex) {
 			Map<String, Object> otherParameters, Integer pageIndex) {
-		String message = "";
 		if (StringUtils.isEmpty(userName)) {
 		if (StringUtils.isEmpty(userName)) {
-			message = "未传入当前账套用户名!";
-			logger.error(message);
-			return null;
+			throw new SystemError("未传入当前账套用户名!");
 		}
 		}
 		if (StringUtils.isEmpty(reportName)) {
 		if (StringUtils.isEmpty(reportName)) {
-			message = "报表名称无效!";
-			logger.error(message);
-			return null;
+			throw new SystemError("报表名称无效!");
 		}
 		}
 
 
 		logger.info("开始预览报表: " + reportName);
 		logger.info("开始预览报表: " + reportName);
 		Map<String, Object> result = printService.preview(userName, reportName, whereCondition, otherParameters,
 		Map<String, Object> result = printService.preview(userName, reportName, whereCondition, otherParameters,
 				pageIndex);
 				pageIndex);
 		byte[] data = null;
 		byte[] data = null;
-		if (!CollectionUtils.isEmpty(result)) {
+		if (result != null && result.get("data") != null) {
 			data = (byte[]) result.get("data");
 			data = (byte[]) result.get("data");
 		}
 		}
-		if (!ArrayUtils.isEmpty(data)) {
-			message = "报表 " + reportName + " 预览完成!";
-			logger.info(message);
-			// 对pdf流进行base64编码
-			result.replace("data", Base64.encodeBase64String(data));
-			return result;
+		if (data == null) {
+			throw new SystemError("获取预览数据失败");
 		}
 		}
-
-		message = "报表 " + reportName + " 预览失败!";
-		logger.error(message);
-		return null;
+		// 对pdf流进行base64编码
+		result.put("data", Base64.encodeBase64String(data));
+		logger.info("预览报表成功:" + reportName);
+		return result;
 	}
 	}
 }
 }

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

@@ -0,0 +1,104 @@
+/*CopyRright (c)2014: <www.usoftchina.com>
+ */
+package com.uas.report.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.report.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
src/main/java/com/uas/report/core/exception/SystemError.java

@@ -0,0 +1,30 @@
+package com.uas.report.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;
+	}
+
+}

+ 20 - 18
src/main/java/com/uas/report/service/impl/PrintServiceImpl.java

@@ -14,17 +14,6 @@ import java.util.Properties;
 
 
 import javax.sql.DataSource;
 import javax.sql.DataSource;
 
 
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Service;
-import org.springframework.util.CollectionUtils;
-import org.springframework.util.StringUtils;
-
-import com.alibaba.druid.pool.DruidDataSource;
-import com.alibaba.druid.pool.DruidDataSourceFactory;
-import com.uas.report.service.PrintService;
-import com.uas.report.util.ContextUtils;
-import com.uas.report.util.ReportConstants;
-
 import net.sf.jasperreports.engine.JRException;
 import net.sf.jasperreports.engine.JRException;
 import net.sf.jasperreports.engine.JasperCompileManager;
 import net.sf.jasperreports.engine.JasperCompileManager;
 import net.sf.jasperreports.engine.JasperExportManager;
 import net.sf.jasperreports.engine.JasperExportManager;
@@ -40,6 +29,18 @@ import net.sf.jasperreports.export.SimpleExporterInput;
 import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
 import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
 import net.sf.jasperreports.export.SimplePdfReportConfiguration;
 import net.sf.jasperreports.export.SimplePdfReportConfiguration;
 
 
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.StringUtils;
+
+import com.alibaba.druid.pool.DruidDataSource;
+import com.alibaba.druid.pool.DruidDataSourceFactory;
+import com.uas.report.core.exception.SystemError;
+import com.uas.report.service.PrintService;
+import com.uas.report.util.ContextUtils;
+import com.uas.report.util.ReportConstants;
+
 /**
 /**
  * 报表打印
  * 报表打印
  * 
  * 
@@ -52,8 +53,8 @@ public class PrintServiceImpl implements PrintService {
 	private static Logger logger = Logger.getLogger(PrintService.class);
 	private static Logger logger = Logger.getLogger(PrintService.class);
 
 
 	@Override
 	@Override
-	public byte[] export(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters,
-			String exportFileType) {
+	public byte[] export(String userName, String reportName, String whereCondition,
+			Map<String, Object> otherParameters, String exportFileType) {
 		Map<String, Object> result = print(userName, reportName, whereCondition, otherParameters, exportFileType, null);
 		Map<String, Object> result = print(userName, reportName, whereCondition, otherParameters, exportFileType, null);
 		if (!CollectionUtils.isEmpty(result)) {
 		if (!CollectionUtils.isEmpty(result)) {
 			return (byte[]) result.get("data");
 			return (byte[]) result.get("data");
@@ -81,7 +82,7 @@ public class PrintServiceImpl implements PrintService {
 	private Map<String, Object> print(String userName, String reportName, String whereCondition,
 	private Map<String, Object> print(String userName, String reportName, String whereCondition,
 			Map<String, Object> otherParameters, String exportFileType, Integer pageIndex) {
 			Map<String, Object> otherParameters, String exportFileType, Integer pageIndex) {
 		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(reportName)) {
 		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(reportName)) {
-			return null;
+			throw new SystemError("参数错误");
 		}
 		}
 
 
 		// 报表路径为报表根路径REPORT_DIR + 当前账套用户名userName
 		// 报表路径为报表根路径REPORT_DIR + 当前账套用户名userName
@@ -94,7 +95,7 @@ public class PrintServiceImpl implements PrintService {
 		// 报表模板不存在
 		// 报表模板不存在
 		if (!jrxmlFile.exists()) {
 		if (!jrxmlFile.exists()) {
 			logger.error("未发现模板文件: " + jrxmlFile.getPath());
 			logger.error("未发现模板文件: " + jrxmlFile.getPath());
-			return null;
+			throw new SystemError("未发现模板文件: " + jrxmlFile.getPath());
 		}
 		}
 
 
 		String jasperFilePath = jrxmlFile.getPath().replace(".jrxml", ".jasper");
 		String jasperFilePath = jrxmlFile.getPath().replace(".jrxml", ".jasper");
@@ -115,7 +116,8 @@ public class PrintServiceImpl implements PrintService {
 				}
 				}
 			}
 			}
 		} catch (JRException e) {
 		} catch (JRException e) {
-			e.printStackTrace();
+			logger.error(e);
+			throw new SystemError("编译报表模板失败");
 		}
 		}
 
 
 		// 向报表模板传递参数:报表路径、where条件、其他参数
 		// 向报表模板传递参数:报表路径、where条件、其他参数
@@ -133,7 +135,7 @@ public class PrintServiceImpl implements PrintService {
 			// 获取数据源
 			// 获取数据源
 			DataSource dataSource = getDataSource(userName);
 			DataSource dataSource = getDataSource(userName);
 			if (dataSource == null) {
 			if (dataSource == null) {
-				return null;
+				throw new SystemError("获取数据源失败");
 			}
 			}
 
 
 			connection = dataSource.getConnection();
 			connection = dataSource.getConnection();
@@ -176,7 +178,7 @@ public class PrintServiceImpl implements PrintService {
 				return result;
 				return result;
 			} else {
 			} else {
 				logger.error("exportFileType 和 pageSize 不能同时为空!");
 				logger.error("exportFileType 和 pageSize 不能同时为空!");
-				return null;
+				throw new SystemError("exportFileType 和 pageSize 不能同时为空!");
 			}
 			}
 		} catch (SQLException e) {
 		} catch (SQLException e) {
 			logger.error("数据库连接错误!");
 			logger.error("数据库连接错误!");