|
@@ -0,0 +1,72 @@
|
|
|
|
|
+/*CopyRright (c)2014: <www.usoftchina.com>
|
|
|
|
|
+ */
|
|
|
|
|
+package com.uas.report.exception;
|
|
|
|
|
+
|
|
|
|
|
+import java.io.IOException;
|
|
|
|
|
+
|
|
|
|
|
+import javax.servlet.http.HttpServletResponse;
|
|
|
|
|
+
|
|
|
|
|
+import org.slf4j.Logger;
|
|
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
|
|
+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.alibaba.fastjson.JSONObject;
|
|
|
|
|
+import com.uas.report.util.ExceptionUtils;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * 基于Application的异常处理,以AOP的形式注册到SpringMVC的处理链
|
|
|
|
|
+ *
|
|
|
|
|
+ * @author sunyj
|
|
|
|
|
+ * @since 2017年7月13日 上午10:28:37
|
|
|
|
|
+ */
|
|
|
|
|
+@ControllerAdvice
|
|
|
|
|
+public class ExceptionHandlerAdvice {
|
|
|
|
|
+
|
|
|
|
|
+ private static Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 处理已捕获异常,明确传达给客户端错误码、错误信息
|
|
|
|
|
+ *
|
|
|
|
|
+ * @param e
|
|
|
|
|
+ * @return
|
|
|
|
|
+ */
|
|
|
|
|
+ @ExceptionHandler(Throwable.class)
|
|
|
|
|
+ public ResponseEntity<ModelMap> handleError(Throwable e) {
|
|
|
|
|
+ logger.error("", e);
|
|
|
|
|
+ ModelMap map = new ModelMap();
|
|
|
|
|
+ map.put("success", false);
|
|
|
|
|
+ map.put("message",
|
|
|
|
|
+ ExceptionUtils.getMessage(e).replace("\n", "<br/>").replace("\t", " "));
|
|
|
|
|
+ map.put("detailedMessage",
|
|
|
|
|
+ ExceptionUtils.getDetailedMessage(e).replace("\n", "<br/>").replace("\t", " "));
|
|
|
|
|
+ HttpHeaders headers = new HttpHeaders();
|
|
|
|
|
+ headers.add("Content-Type", "application/json; charset=utf-8");
|
|
|
|
|
+ return new ResponseEntity<ModelMap>(map, headers, HttpStatus.INTERNAL_SERVER_ERROR);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 处理错误
|
|
|
|
|
+ *
|
|
|
|
|
+ * @param response
|
|
|
|
|
+ * @param status
|
|
|
|
|
+ * @param message
|
|
|
|
|
+ * @param ip
|
|
|
|
|
+ * @throws IOException
|
|
|
|
|
+ */
|
|
|
|
|
+ public static void handleError(HttpServletResponse response, Integer status, String message, String ip)
|
|
|
|
|
+ throws IOException {
|
|
|
|
|
+ logger.error(message + ":" + ip);
|
|
|
|
|
+ response.setHeader("Content-type", "text/html;charset=UTF-8");
|
|
|
|
|
+ response.setStatus(status);
|
|
|
|
|
+ JSONObject jsonObject = new JSONObject();
|
|
|
|
|
+ jsonObject.put("success", false);
|
|
|
|
|
+ jsonObject.put("message", message);
|
|
|
|
|
+ response.getWriter().println(jsonObject);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+}
|