java: 统一异常处理+自定义异常

背景:在日常开发中,需要经常处理异常;本文主要是讲述统一异常处理和自定义异常处理,统一异常处理是处理编译运行时候系统抛出的异常,是非检查异常UncheckedException ;

 自定义异常是自己根据实际业务情况自定义抛出的异常。

上代码

1.统一异常处理

@RestControllerAdvice //这个注解标记得类都表示全局异常处理类,并返回json数据格式
@ExceptionHandler(value = Exception.class) // value可以指定处理哪种异常, Exception处理所有异常。

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception ex){
        ex.printStackTrace();//输出异常,日志文件
        log.error(ex.getMessage());
        return R.error().message(ex.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public R handleRuntimeException(RuntimeException runtimeException){
        runtimeException.printStackTrace();//输出异常,日志文件
        log.error(runtimeException.getMessage());
        return R.error().message("编译时异常");
    }

    @ExceptionHandler(value = SQLException.class)
    public R handleSqlException(SQLException sqlException){
        sqlException.printStackTrace();//输出异常,日志文件
        log.error(sqlException.getMessage());
        return R.error().message("SQL异常");
    }

    @ExceptionHandler(value = ArithmeticException.class)
    public R handleArithmeticException(ArithmeticException arithmeticException){
        arithmeticException.printStackTrace();//输出异常,日志文件
        log.error(arithmeticException.getMessage());
        return R.error().message("数字异常");
    }

    //自定义的异常实际开发中必须手动抛出
    @ExceptionHandler(value = StudentException.class)
    public R handleYyghException(StudentException studentException){
        studentException.printStackTrace();//输出异常,日志文件
        log.error(studentException.getMessage());
        return R.error().message(studentException.getMessage()).code(studentException.getCode());
    }
}

2.自定义异常

需要继承RuntimeException接口

代码:


@Data
public class StudentException  extends RuntimeException{
    private Integer code;
    private String message;

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

3.测试

 结果:

结束! 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值