通用异常

本文详细介绍了如何在Java中自定义异常处理机制,包括创建枚举类型的异常信息、定义自定义异常类、实现统一异常结果类、配置异常处理器以及实际应用示例。这将帮助开发者更好地管理和响应程序运行时可能出现的各种异常情况。

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

1、自定义异常类型参数的枚举类型

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnums {
    PRICE_CONNT_BE_NULL(400,"价格不能是空");
    private int code;
    private String msg;
}

2、自定义异常

import com.leyou.common.enums.ExceptionEnums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class LyException extends RuntimeException {
    private ExceptionEnums exceptionEnums;
}

3、定义统一的异常结果

import com.leyou.common.enums.ExceptionEnums;
import lombok.Data;

@Data
public class ExceptionResult {
    private int status;
    private String message;
    private Long timestamp;

    public ExceptionResult(ExceptionEnums em) {
        this.status=em.getCode();
        this.message=em.getMsg();
        this.timestamp=System.currentTimeMillis();
    }
}

4定义异常处理器

import com.leyou.common.exception.LyException;
import com.leyou.common.vo.ExceptionResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice  //表示处理带有Controller注解的类
public class CommonExceptionHandler {

    @ExceptionHandler(LyException.class)    //表明拦截的异常类型,这里拦截自己定义的异常
    public ResponseEntity<ExceptionResult> handleExceprion(LyException e){
        return ResponseEntity.status(e.getExceptionEnums().getCode())//通过ResponseEntity设置返回的状态,并且获得状态
                .body(new ExceptionResult(e.getExceptionEnums()));
    }
}

5、使用

throw new LyException(ExceptionEnums.PRICE_CONNT_BE_NULL);

 

转载于:https://www.cnblogs.com/feixiangdecainiao/p/10853665.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值