通用异常

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