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

Posted coding++

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了coding++:java-全局异常处理相关的知识,希望对你有一定的参考价值。

本次使用工具: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-全局异常处理的主要内容,如果未能解决你的问题,请参考以下文章

Java中的全局异常处理

Java异常处理机制

Java中的全局异常处理

Java中的全局异常处理

Java中的全局异常处理

SpringBoot全局异常处理