簡體   English   中英

ControllerAdvice 有條件地處理異常

[英]ControllerAdvice conditionally handle exception

I have a controller advice that handles the exceptional behavior in my REST controller and I came across a situation when I have to conditionally process SQLIntegrityConstraintViolationException that have a certain message (the one for duplicate keys), returning a 409 , letting the other ones be handled由默認處理程序(返回500錯誤代碼)。

我正在考慮兩種可能的方法來實現這一目標:

  1. 根據我的情況在 else 分支上拋出一個新的准系統Exception ,因此處理由 Spring 完成。
  2. 顯式調用通用異常處理程序(例如從我的 else 分支中return handleGeneralException(exception) )。

我有一種“正確”的方式可以將我的ControllerAdvice中的一小部分異常傳遞給另一個處理程序,而不是“原始”處理程序?

編輯1:我想在我的ControllerAdvice中做這樣的事情:

if (exception.getMessage.contains("something")) {
    // handle exception
} else {
    // pass to other handler
}

有一個自定義異常 class ,然后當您拋出SQLIntegrityConstraintViolationException時,將其包裝在您的自定義異常類中,其中包含您希望在 controller 建議中訪問的任何附加字段。 處理 controller 建議 class 中的自定義異常。

@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(YourCustomException.class)
    public final ResponseEntity<ExceptionResponse> handleNotFoundException(YourCustomExceptionex,
            WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
                request.getDescription(false), HttpStatus.NOT_ACCEPTABLE.getReasonPhrase());
        return new ResponseEntity<>(exceptionResponse, HttpStatus.CONFLICT);
    }

}

在使用 try catch 塊來處理代碼中的此異常時,如果您使用Spring 數據 JPA ,請確保處理DataIntegrityViolationException而不是SQLIntegrityConstraintViolationException 因此,如果您使用的是 Spring 數據 Jpa 則:

try {
    anyRepository.save(new YourModel(..));
} catch (DataIntegrityViolationException e) {
    System.out.println("history already exist");in res
    throw New YourCustomException("additional msg if you need it ", e);
}

下面的代碼將在ControllerAdbvice中捕獲異常SQLIntegrityConstraintViolationException的錯誤消息,而無需在代碼中處理

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = DataIntegrityViolationException.class)
public ResponseEntity<ExceptionResponse> dataIntegrityViolationExceptionHandler(Exception ex) {
ExceptionResponse response = new ExceptionResponse();
    Throwable throwable = ex.getCause();
    while (throwable != null) {
        if (throwable instanceof SQLIntegrityConstraintViolationException) {
            String errorMessage = throwable.getMessage();
            response.setErrors(new ArrayList<>(Arrays.asList(errorMessage)));
        }
        throwable = throwable.getCause();
    }       
    return new ResponseEntity<Object>(response, HttpStatus.CONFLICT);
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM