coding++:java-全局異常處理

本次使用工具:SpringBoot   <version>1.5.19.RELEASE</version>java

Code:web

 

AbstractException:ajax

package mlq.global.anomaly.exception; import mlq.global.anomaly.utils.ErrorPrintUtils; public abstract class AbstractException extends RuntimeException { private static final long serialVersionUID = -5992753399315247713L; private String errorCode; private String errorMsg; private String stackTraceMsg; private String level; private String messageID; private boolean sendMsg = true; public AbstractException(String code, String message, String... level) { super(code + "|" + message); this.handleExceptionMessage(code, message, code + "|" + message); } public AbstractException(String code, String message, Throwable th) { super(code + "|" + message, th); this.handleExceptionMessage(code, message, ErrorPrintUtils.printStackTrace(th)); } public final void handleExceptionMessage(String code, String message, String stackTraceMsg) { this.errorCode = code; this.errorMsg = message; this.stackTraceMsg = stackTraceMsg; } public AbstractException(Throwable cause) { super(cause); ErrorDesc errorDesc = this.getErrorDesc(cause); if (errorDesc != null) { this.errorCode = errorDesc.errorCode; this.errorMsg = errorDesc.errorMsg; } } public AbstractException(String message) { super(message); } public abstract ErrorDesc getErrorDesc(Throwable var1); public String getErrorCode() { return this.errorCode; } public String getErrorMsg() { return this.errorMsg; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public String getStackTraceMsg() { return this.stackTraceMsg; } public void setStackTraceMsg(String stackTraceMsg) { this.stackTraceMsg = stackTraceMsg; } public String getLevel() { return this.level; } public void setLevel(String level) { this.level = level; } public String getMessageID() { return this.messageID; } public void setMessageID(String messageID) { this.messageID = messageID; } public boolean isSendMsg() { return this.sendMsg; } public void setSendMsg(boolean sendMsg) { this.sendMsg = sendMsg; } public static class ErrorDesc { public String errorCode; public String errorMsg; public ErrorDesc(String errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } } }
AbstractException

NoveControllerException:spring

package mlq.global.anomaly.exception; public class NoveControllerException extends AbstractException { private static final long serialVersionUID = 8307533385237791476L; public NoveControllerException(String code, String message) { super(code, message, new String[0]); } public NoveControllerException(String code, String message, Throwable th) { super(code, message, th); } public AbstractException.ErrorDesc getErrorDesc(Throwable var1) { return null; } }
NoveControllerException

CustomException:json

package mlq.global.anomaly.exception; /** * 自定義 異常類 */
public class CustomException extends NoveControllerException { private static final long serialVersionUID = 1L; public CustomException(String code, String message) { super(code, message); } public CustomException(String code, String message, Throwable th) { super(code, message, th); } }
CustomException

JsonException:ide

package mlq.global.anomaly.exception; /** * 自定義 JsonException */
public class JsonException extends NoveControllerException { private static final long serialVersionUID = -5605565877150120787L; public JsonException(String code, String message) { super(code, message); } public JsonException(String code, String message, Throwable th) { super(code, message, th); } }
JsonException

ErrorPrintUtils:工具

package mlq.global.anomaly.utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; public class ErrorPrintUtils { public ErrorPrintUtils() { } public static String printStackTrace(Throwable exception) { StringWriter sw = null; PrintWriter pw = null; try { sw = new StringWriter(); pw = new PrintWriter(sw); exception.printStackTrace(pw); } finally { if (sw != null) { try { sw.close(); } catch (IOException var8) { ; } } if (pw != null) { pw.close(); } } return sw.toString(); } }
ErrorPrintUtils

GlobalExceptionHandler:this

package mlq.global.anomaly.exception; import com.alibaba.fastjson.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * 全局異常類 */ @ControllerAdvice public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { LOGGER.info("Exception異常"); LOGGER.info("RequestURL:url={}", request.getRequestURL()); LOGGER.error("請求地址:url={},系統異常:error={}", request.getRequestURL(), e); if (!checkAjaxRequest(request)) { ModelAndView mav = new ModelAndView("500"); mav.addObject("exception", e); mav.addObject("reqUrl", request.getRequestURL()); return mav; } else { ModelAndView mv = new ModelAndView(); // 設置狀態碼
 response.setStatus(HttpStatus.OK.value()); // 設置ContentType
 response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 設置編碼格式 避免亂碼
            response.setCharacterEncoding("UTF-8"); // 頭部響應信息
            response.setHeader("Cache-Control", "no-cache, must-revalidate"); // 返回結果
            response.getWriter().write("{\"resultCode\":500,\"message\":\"" + e.getMessage() + "\"}"); return mv; } } /** * 自定義異常 * * @throws Exception */ @ExceptionHandler(value = CustomException.class) public ModelAndView callCenterHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception { LOGGER.info("自定義異常"); LOGGER.info("RequestURL:url={}", req.getRequestURL()); LOGGER.error("請求地址:url={},CallCenterException異常:error={}", req.getRequestURL(), e); if (!checkAjaxRequest(req)) { ModelAndView mav = new ModelAndView("500"); mav.addObject("exception", e.getMessage()); mav.addObject("reqUrl", req.getRequestURL()); return mav; } else { ModelAndView mv = new ModelAndView(); response.setStatus(HttpStatus.OK.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache, must-revalidate"); response.getWriter().write("{\"resultCode\":500,\"message\":\"" + e.getMessage() + "\"}"); return mv; } } @ExceptionHandler(value = JsonException.class) @ResponseBody public Map<String, Object> jsonErrorHandler(HttpServletRequest req, JsonException e) throws Exception { LOGGER.info("JSON異常"); LOGGER.info("RequestURL={}", req.getRequestURL()); LOGGER.error("請求地址:url={},ajax請求異常:error={}", req.getRequestURL(), e); Map<String, Object> map = Collections.synchronizedMap(new HashMap<String, Object>()); map.put("resultCode", 500); map.put("message", e.getMessage()); return map; } /** * 判斷是否ajax請求 * * @param request * @return
     */
    private boolean checkAjaxRequest(HttpServletRequest request) { String requestType = request.getHeader("X-Requested-With"); if (!ObjectUtils.isEmpty(requestType) && "XMLHttpRequest".equals(requestType)) { return true; } return false; } }
GlobalExceptionHandler

提示:在沒有異常自行處理的時候  就會走全局異常類編碼

相關文章
相關標籤/搜索