直接抄答案:异常处理

本文介绍了在SpringMVC应用中,如何使用GuiguException进行统一的异常管理和处理,包括全局异常处理、特定异常处理(如除0异常)以及自定义异常的响应格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.atguigu.common.config.exception;


import com.atguigu.com.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;


    }

    /**
     * 接收枚举类型对象
     */

    public GuiguException(ResultCodeEnum resultCodeEnum){
        super(resultCodeEnum.getMessage());
        this.code = resultCodeEnum.getCode();
        this.msg = resultCodeEnum.getMessage();
    }

    public String toString(){

        return "GuliException{ " +
                "code = " + code +
                ",message=" + this.getMessage() +
                '}';
    }

}
    






package com.atguigu.common.config.exception;


import com.atguigu.com.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 GlobExceptionHandler {


    // 全局异常处理 执行的方法

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e){

        e.printStackTrace();
        return Result.fail().message("执行全局异常处理..");
    }

    // 特定异常处理
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e) {
        e.printStackTrace();
        return Result.fail().message("除0异常");
    }


    // 自定义异常处理
    @ExceptionHandler(GuiguException.class)
    @ResponseBody
    public Result error(GuiguException e){
        e.printStackTrace();
        return Result.fail().code(e.getCode()).message(e.getMsg());
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值