Java 自定义系统异常

在Java系统中,为了更清楚展示异常信息,通常需要自定义异常。

在exception包中,需要定义一个RestErrorResponse类与前端约定返回的异常信息模型。

@Data
public class RestErrorResponse implements Serializable{

    private String errMessage;

    public RestErrorResponse(errMessage){

        this.errMessage = errMessage;
    }    
    
    public String getErrMessage(){

        return errMessage;
    }

    public void setErrMessage(){

        this.errMessage = errMessage;
    }
}

除此之外,我们可以写一个自定义异常类继承RuntimeException,重写构造方法。

public class DIYException extends RuntimeException{

    private String errMessage;

    public DIYException(){
    }

    public DIYException(String errMessage){

        super(errMessage);
        this.errMessage = errMessage;
    }

    public static void cast(String errMessage){

        throw new RuntimeException(errMessage);
    }

    public static void cast(CommonError errMessage){

        throw new RuntimeExceprion(errMessage);
    }
}

一些通用的异常信息,可以通过创建枚举类实现。

public enum CommonError{

    UNKNOW_ERROR("执行过程异常,请重试");
    PARAMS_ERROR("非法参数");
    OBJECT_NULL("对象为空");
    QUERY_NULL("查询结果为空");
    REQUEST_NULL("请求蚕食为空");

    private String errMessage;

    private String getErrMessage(){

        return errMessage;
    }

    private CommonError(String errMessage){

        this.errMessage = errMessage;
    }
}

定义全局异常处理器

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler{

    @Responsebody
    @ExceptionHandler(DIYException.class)
    @ResponseSttus(HttpStatus.INTERNAL.SERVER.ERROR)
    public RestErrorResponse customException(DIYException e){

        log.error("系统异常{}",e.getErrMessage(),e)

        String errMessage = e.getErrMessage();
        RestErrorResponse restErrorResponse = new RestErrorResponse(errMessage);
        return restErrorResponse;
    }



    @Responsebody
    @ExceptionHandler(Exception.class)
    @ResponseSttus(HttpStatus.INTERNAL.SERVER.ERROR)
    public RestErrorResponse customException(Exception e){

        log.error("系统异常{}",e.getMessage(),e)

        RestErrorResponse restErrorResponse = new RestErrorResponse(CommonError.UNKNOWN_ERROR.getErrMessage());
        return restErrorResponse;
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值