栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring全局异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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里面的内容

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/434925.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号