-----------------------------------------自定義異常類------------------------------------------
// 自定義異常類
@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 {
@Autowired
private ItemService itemService;
@PostMapping
public 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
}