Spring提供了同意的異常處理註解,用戶只需要在錯誤的時候提示信息即可
- 實現方式:
- 在類上添加@ControllerAdvice註解
- 在方法上添加@ExceptionHandler註解
例如:
1. 自定義一個異常 AbstractApolloHttpException public class AbstractApolloHttpException extends RuntimeException{ private static final long serialVersionUID = -1713129594004951820L; public AbstractApolloHttpException(String msg){ super(msg); } public AbstractApolloHttpException(String msg, Exception e){ super(msg,e); } } 2. 自定義同意異常的處理類 GlobalDefaultExceptionHandler @ControllerAdvice public class GlobalDefaultExceptionHandler { //處理自定義Exception @ExceptionHandler({AbstractApolloHttpException.class}) public ResponseEntity<Map<String, Object>> badRequest(HttpServletRequest request, AbstractApolloHttpException ex) { return handleError(request, ex.getHttpStatus(), ex); } private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request, HttpStatus status, Throwable ex) { return handleError(request, status, ex, ERROR); } }