-----------------------------------------自定义异常类------------------------------------------
// 自定义异常类
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class MyException extends RuntimeException {private ExceptionEnum exceptionEnum;
}
-----------------------------------------------------------定义异常枚举--------------------------------------------------------------
@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum ExceptionEnum {PRICE_CANNOT_BE_NULL(400,"价格不能为空");private int code;private String msg;
}
-----------------------------------------------------------定义异常返回对象--------------------------------------------------------------
@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();}
}
-----------------------------------------------------------定义异常捕捉类--------------------------------------------------------------
@ControllerAdvice
public class CommonExceptionHandler {@ExceptionHandler(MyException.class)public ResponseEntity<ExceptionResult> handleException(MyException exception) {return ResponseEntity.status(exception.getExceptionEnum().getCode()).body(new ExceptionResult(exception.getExceptionEnum()));}
}
-----------------------------------------------------------方法调用--------------------------------------------------------------
@RestController
@RequestMapping("item")
public class ItemController {@Autowiredprivate ItemService itemService;@PostMappingpublic ResponseEntity<Item> saveItem(Item item) {if (item.getPrice() == null) {throw new MyException(ExceptionEnum.PRICE_CANNOT_BE_NULL);}item = itemService.saveItem(item);return ResponseEntity.status(HttpStatus.CREATED).body(item);}
}
---------------------------------------------------返回结果----------------------------------------
{
"status": 400,
"message": "价格不能为空",
"timestamp": 1572315505000
}