有沒有辦法在知道哪個方法導致此例外的情況下攔截DataAccessException資料層(@Repository)拋出的資料?
撰寫自定義SQLExceptionTranslator不符合我的需要,因為我無法確定導致例外的方法。
我有一個這樣的存盤庫:
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
@ErrorCode("E1000")
User findById(int id);
@ErrorCode("E1001")
User findByUsername(String username);
}
ErrorCode是一個自定義注釋,包含一個錯誤代碼,我需要在DataAccessException發生時將其發送給客戶端。
如果有辦法攔截對findByIdwith DataAccessExceptioncatch的呼叫,那么很容易從注解中提取錯誤代碼并重新拋出一個可以被例外處理程式捕獲的自定義例外。
uj5u.com熱心網友回復:
如果允許 Spring AOP,您可以構建自己的方面,例如:
@Aspect
public class ErrorCodeAspect {
@Around("@annotation(errorCode)")
public Object aroundErrorCode(ProceedingJoinPoint joinPoint, ErrorCode errorCode) throws Throwable {
try {
return joinPoint.proceed();
} catch (DataAccessException dae) {
throw new YourCustomException(errorCode.value(), dae);
}
}
}
請注意,介面方法的注解不是通過實作類方法繼承的(即使@Inherited僅適用于父類),因此您可能需要注解您的具體服務類而不是插入方面(除非 Spring 做了一些額外的黑魔法使用我不知道的存盤庫代理)。
uj5u.com熱心網友回復:
您可以定義自定義ExceptionHandler.
@RestControllerAdvice
public class RestExceptionResolver {
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<String> handleNoSuchElementException(DataAccessException ex) {
return ResponseEntity.status(yourErrorCode);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327877.html
