JAVA项目中自定义异常

JAVA项目中自定义异常

1.数据返回处理类

@Data
public class R<T> implements Serializable {


    private static final long serialVersionUID = -8497670085742879369L;


    @ApiModelProperty(value = "返回码", example = "200")
    private Integer code=200;

    @ApiModelProperty(value = "返回消息", example = "")
    private String message="SUCCESS";

    @ApiModelProperty(value = "返回数据", example = "")
    private T data;

    private R() {
    }

    public R(T data) {
        this.data = data;
    }


    public R(Integer code,String message) {
        this.code=code;
        this.message = message;
    }



}

2.新建自定义异常

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GuliException extends  RuntimeException{

    private Integer code;

    private String msg;
}

3.定义异常处理

@ControllerAdvice
public class GlobalExceptionHandler {


    //指定出现什么异常执行这个方法
    @ExceptionHandler(GuliException.class)
    @ResponseBody  //返回数据
    public R error(GuliException e){
        e.printStackTrace();
        return new R(e.getCode(),e.getMsg());
    }
}

4.不使用异常处理示例

   @GetMapping("/testError")
    @ApiOperation(value = "测试异常处理")
    public R<UserVO> testError(@RequestParam("id") String id){
        UserVO userVO=new UserVO();
        SysUser byId = sysUserService.getById(id);
        BeanUtils.copyProperties(byId,userVO);

        return new R<>(userVO);
    }

执行结果
在这里插入图片描述
使用自定义异常

 @GetMapping("/testCheck")
    @ApiOperation(value = "测试返回值正常处理")
    public R<Boolean> testCheck(){
           try {
               int i=10/0;
           }catch (Exception e){
               e.printStackTrace();
               throw new GuliException(1001,"错误测试");
           }
        return  new R<>(true);
    }

执行结果
在这里插入图片描述
全局异常定义
在这里插入图片描述

如果有异常Exception会被这里的全局异常捕捉,并抛出

持续更新!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱上编程2705

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值