首页 > 其他 > 详细

通用异常

时间:2019-05-12 21:20:18      阅读:740      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!