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

springboot统一异常处理

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

springboot统一异常处理

新建Java类

package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

//集中处理异常类
@Slf4j
//处理哪个包下出现的异常
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExxceptionControllerAdvice {

    //处理MethodArgumentNotValidException的异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
    //下方是处理MethodArgumentNotValidException的异常处理方法,根据不同异常修改
    //MethodArgumentNotValidException异常是@Valid校验异常
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map errorMap = new HashMap<>();
        //获取校验的错误结果
        result.getFieldErrors().forEach(item->{
            errorMap.put(item.getField(),item.getDefaultMessage());
        });
        //最后将异常返回出去
        //BizCodeEnume是异常状态的枚举,分别是code和msg可自己定义
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
    }

	//Exception异常是所有异常如果非上方的特定异常,都在这里处理
    @ExceptionHandler(value = Exception.class)
    public R handleException(Throwable throwable){

        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}

//异常枚举
package com.atguigu.common.exception;

public enum BizCodeEnume {
    UNKNOW_EXCEPTION(10000,"系统未知异常"),

    VAILD_EXCEPTION(10001,"参数格式校验失败");

    private int code;

    private String msg;

    BizCodeEnume(int code,String msg){
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

}

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

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

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