码迷,mamicode.com
首页 > 编程语言 > 详细

coding++:java-全局异常处理

时间:2019-11-08 10:53:48      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:null   result   servlet   write   eid   tst   orm   lte   fast   

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

Code:

技术图片

 

AbstractException:

 

技术图片
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:

 

技术图片
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:

 

技术图片
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:

 

技术图片
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:

 

技术图片
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

 

提示:在没有异常自行处理的时候  就会走全局异常类

 

 

 

coding++:java-全局异常处理

标签:null   result   servlet   write   eid   tst   orm   lte   fast   

原文地址:https://www.cnblogs.com/codingmode/p/11818633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!