可以先定义一个枚举类
import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor @AllArgsConstructor public enum ExceptionEnum { PRICE_CANNOT_BE_NULL(400,"价格不能为空!"), CATEGORY_NOT_FOUND(404,"商品分类没查到"), ; private int code; private String msg; }
然后定义一个异常继承EuntimeException
import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor @Getter public class LyException extends RuntimeException{ private ExceptionEnum exceptionEnum; }
然后在controller层做拦截
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 public class CommonExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<ExceptionResult> handleException(LyException e){ ExceptionEnum em = e.getExceptionEnum(); return ResponseEntity.status(em.getCode()).body(new ExceptionResult(e.getExceptionEnum())); } }
即可
也可以加上下行参数实体
import lombok.Data; @Data public class ExceptionResult { private int status; private String message; private Long timestamp; public ExceptionResult(ExceptionEnum em){ this.status = em.getCode(); this.message = em.getMsg(); this.timestamp = System.currentTimeMillis(); } }