设置全局异常处理 java


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.tele.utils.Constants;
import com.tele.utils.ResultJson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.MessageFormat;

@ControllerAdvice
@ResponseBody
public class GlobalException {
    private static final Logger LOG = LogManager.getLogger(GlobalException.class);

    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";

    // 运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Object runtimeExceptionHandler(RuntimeException ex) {
        return resultFormat(1, ex);
    }

    // 空指针异常
    @ExceptionHandler(NullPointerException.class)
    public String nullPointerExceptionHandler(NullPointerException ex) {
        return resultFormat(2, ex);
    }

    // 类型转换异常
    @ExceptionHandler(ClassCastException.class)
    public String classCastExceptionHandler(ClassCastException ex) {
        return resultFormat(3, ex);
    }

    // IO异常
    @ExceptionHandler(IOException.class)
    public String iOExceptionHandler(IOException ex) {
        return resultFormat(4, ex);
    }

    // 未知方法异常
    @ExceptionHandler(NoSuchMethodException.class)
    public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        return resultFormat(5, ex);
    }

    // 数组越界异常
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        return resultFormat(6, ex);
    }

    // 400错误
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public String requestNotReadable(HttpMessageNotReadableException ex) {
        LOG.error("400..requestNotReadable");
        if (ex.getCause() instanceof InvalidFormatException) {
            InvalidFormatException invalidFormatException = (InvalidFormatException) ex.getCause();
            String reason = MessageFormat.format("字段[{0}]的值[{1}]不能转换成[{2}]类型",
                    new Object[]{invalidFormatException.getPath().get(0).getFieldName()// 字段
                            , invalidFormatException.getValue()// 值
                            , invalidFormatException.getTargetType().getName()});// 类型
            return resultFormat(7, ex, reason);
        }
        return resultFormat(7, ex);
    }

    // 400错误
    @ExceptionHandler({TypeMismatchException.class})
    public String requestTypeMismatch(TypeMismatchException ex) {
        LOG.error("400..TypeMismatchException");
        return resultFormat(8, ex);
    }

    // 参数异常处理
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public String methodNotValidHandler(MethodArgumentNotValidException ex) {
        LOG.info("参数异常 ---> ", ex);
        return resultFormat(8, ex);
    }

    // 400错误
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
        LOG.error("400..MissingServletRequest");
        return resultFormat(9, ex);
    }

    // 405错误
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public String request405(HttpRequestMethodNotSupportedException ex) {
        return resultFormat(10, ex);
    }

    // 406错误
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    public String request406(HttpMediaTypeNotAcceptableException ex) {
        LOG.error("406...");
        return resultFormat(11, ex);
    }

    // 500错误
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public String server500(RuntimeException ex) {
        LOG.error("500...");
        return resultFormat(12, ex);
    }

    // 栈溢出
    @ExceptionHandler({StackOverflowError.class})
    public String requestStackOverflow(StackOverflowError ex) {
        return resultFormat(13, ex);
    }

    // 其他错误
    @ExceptionHandler({Exception.class})
    public String exception(Exception ex) {
        return resultFormat(14, ex);
    }

    private <T extends Throwable> String resultFormat(Integer code, T ex, String cause) {
        LOG.error(String.format(logExceptionFormat, code, ex));
        ResultJson r = ResultJson.fail(Constants.RESULT_EXCEPTION, cause);
        return JSON.toJSONString(r);
    }

    private <T extends Throwable> String resultFormat(Integer code, T ex) {
        LOG.error("发生异常 = {}", ex.getMessage(), ex);
        ResultJson r = ResultJson.fail(Constants.RESULT_EXCEPTION, ex.getMessage());
        return JSON.toJSONString(r);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值