不说废话,直接开怼(如果不知道@data和@Getter等注解可以了解下lombok,装个插件,爽得一逼)
1.定义一个异常的枚举类
package cn.carryshuai.自定义异常处理.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnum {
PRICE_CANNOT_BE_NULL(400, "价格不能为空"),
PARAM_CANNOT_BE_NULL(400, "参数不能为空"),
CATEGORY_NOT_FOUND(404, "商品分类没有找到"),
SPEC_GROUP_NOT_FOUND(404, "商品规格组没有查到"),
BRAND_SAVE_ERROR(500, "新增品牌失败"),
GOODS_SAVE_ERROR(500, "新增商品失败"),
BRAND_NOT_FOUND(404, "品牌没有找到"),
UPLOAD_FILE_ERROR(500, "文件上传失败"),
INVALID_FILE_TYPE(400, "无效文件类型"),
SPEC_PARAM_NOT_FOUND(404,"商品规格参数不存在"),
GOODS_NOT_FOUND(404,"商品不存在"),
SPU_DETAIL_NOT_FOUND(404, "商品详情不存在"),
GOODS_SKU_NOT_FOUND(404,"sku没有找到");
private int code;
private String msg;
}
2.定义一个异常的结果集
package cn.carryshuai.自定义异常处理.vo;
import cn.carryshuai.自定义异常处理.enums.ExceptionEnum;
import lombok.Data;
@Data
public class ExceptionResult {
private int status;
private String message;
private Long timestamp;
public ExceptionResult(ExceptionEnum exceptionEnum) {
this.status = exceptionEnum.getCode();
this.message = exceptionEnum.getMsg();
this.timestamp = System.currentTimeMillis();
}
}
3.自定义一个异常,继承RunTimeException,里面放着定义的枚举类
package cn.carryshuai.自定义异常处理.exception;
import cn.carryshuai.自定义异常处理.enums.ExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class CarryExcepttion extends RuntimeException {
private ExceptionEnum exceptionEnum;
}
4.创建一个通知,拦截异常
package cn.carryshuai.自定义异常处理.advice;
import cn.carryshuai.自定义异常处理.enums.ExceptionEnum;
import cn.carryshuai.自定义异常处理.exception.CarryExcepttion;
import cn.carryshuai.自定义异常处理.vo.ExceptionResult;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* 拦截异常
*/
@ControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(CarryExcepttion.class)
public ResponseEntity handleException(CarryExcepttion carryExcepttion){
ExceptionEnum em = carryExcepttion.getExceptionEnum();
return ResponseEntity.status(em.getCode()).body(new ExceptionResult(em));
}
}
5.使用自定义的异常
6.异常效果截图