java异常处理

全局和特定

package com.atguigu.common.config.exception;
import com.atguigu.common.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 全局异常处理类
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    //出现那种异常时执行
    @ExceptionHandler(Exception.class)
    //返回json数据所需要的,为了能返回json数据
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail().message("执行全局异常处理....");
    }

    //特定异常处理
    //出现那种异常时执行
    @ExceptionHandler(ArithmeticException.class)
    //返回json数据所需要的,为了能返回json数据
    @ResponseBody
    public Result error(ArithmeticException e){
        e.printStackTrace();
        return Result.fail().message("执行特定异常处理....");
    }
}

 自定义异常处理

1  创建异常类,继承RuntimeExceeption

package com.atguigu.common.config.exception;

import com.atguigu.common.result.ResultCodeEnum;
import lombok.Data;

@Data
public class GuiguException extends RuntimeException {
    private Integer code;
    private String msg;

    public GuiguException(Integer code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    /**
     * 接收枚举类型对象
     * @param resultCodeEnum
     */
    public GuiguException(ResultCodeEnum resultCodeEnum) {
        super(resultCodeEnum.getMessage());
        this.code = resultCodeEnum.getCode();
        this.msg = resultCodeEnum.getMessage();
    }

    @Override
    public String toString() {
        return "GuliException{" +
                "code=" + code +
                ", message=" + this.getMessage() +
                '}';
    }
}

2 手动抛出异常

//模拟异常效果
        try {
            int i=10/0;
        } catch (Exception e){
            //手动抛出自定义异常
            throw new GuiguException(2001,"处理了自定义异常!");
        }

3 添加执行方法

 //自定义异常处理
    //出现那种异常时执行
    @ExceptionHandler(GuiguException.class)
    //返回json数据所需要的,为了能返回json数据
    @ResponseBody
    public Result error(GuiguException e){
        e.printStackTrace();
        return Result.fail().code(e.getCode()).message(e.getMsg());
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值