spring全局异常处理

先来看下没加全局异常,发生报错的返回
简短的
在这里插入图片描述
长一点的
在这里插入图片描述
这样报错抛给前端会是一大堆,不方便处理

gatway的全局异常处理只能捕获模块调用间的异常,单独的模块报错还是要用到 @ControllerAdvice

上核心代码

package com.zhzh.config.excep;

import com.zhzh.model.ResultVO;
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.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;


@ControllerAdvice
public class CustomExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultVO errorHandler(Exception ex) {
        String msg ="";

        //判断异常的类型,返回不一样的返回值
        if(ex instanceof MissingServletRequestParameterException){
            msg ="缺少必需参数:"+((MissingServletRequestParameterException) ex).getParameterName();
        }
        else if(ex instanceof IllegalArgumentException){
            msg = "参数不合法";
        }

        else if(ex instanceof NullPointerException){
            msg ="空指针异常";
        }
        else if(ex instanceof ClassCastException){
            msg = "类型强制转换异常";
        }

        else if(ex instanceof ArrayIndexOutOfBoundsException){
            msg ="数组索引越界";
        }
        else if(ex instanceof NumberFormatException){
            msg = "字符串转换为数字异常";
        }

        else if(ex instanceof SQLException){
            msg = "操作数据库异常";
        }

        else if(ex instanceof IOException){
            msg ="输入/输出流异常";
        }
        else if(ex instanceof NoSuchMethodException){
            msg = "方法未找到异常";
        }

        else if(ex instanceof ArithmeticException){
            msg = "数学运算(分母为0)异常";
        }

        else if(ex instanceof ClassNotFoundException){
            msg = "指定的类不存在";
        }

        else{
            msg=ex.getMessage();
        }

        ex.printStackTrace();
        StringWriter errorsWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(errorsWriter));
        String error = errorsWriter.toString();

        ResultVO resultVO = new ResultVO(500,msg, error);
        return resultVO;
    }
}

这里捕获的常见的异常,根据实际使用修改,msg的报错信息可自行修改

测试
在这里插入图片描述
在这里插入图片描述
好像更多了…不过前端只用抛出msg里面的内容

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值