簡體   English   中英

Spring Boot Rest ResponseEntity響應

[英]spring boot rest ResponseEntity responses

春季引導休息還很陌生,並且對如何和使用最佳方式處理對客戶響應的最佳方法有疑問。 當前,我具有以下控制器代碼,用於處理在數據庫查詢中找不到記錄的情況:

@PreAuthorize("hasAuthority('ROLE_USER')")
@GetMapping("distance/{id}")
public ResponseEntity<?> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null){
        return new ResponseEntity<CustomErrorMsg>(new CustomErrorMsg("Distance ID " + id + " Not Found"),HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Distance>(distance, HttpStatus.OK);
}

其中CustomErrorMsg是一個簡單的類,可在其構造函數中設置一個String。

這是最好的方法嗎? 基於ControllerAdvice的類會更好嗎? 之所以問這個問題,是因為上面的代碼在未經許可的情況下被科學家調用時會發送預期的403響應。 想了解這是怎么發生的,以及是否可以將其用於NOT FOUND條件。

“找不到資源”是一個眾所周知的用例,對於該用例,您不必借助ResponseEntity或ControllerAdvice來“加深”。 您可以簡單地使用ResourceNotFoundException

@PreAuthorize("hasRole('USER')")
@GetMapping("distance/{id}")
public Distance getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null) {
        throw new ResourceNotFoundException("Distance ID " + id + " Not Found");
    }

    return distance;
}

ResponseEntity<?>聲明為返回類型是正確的,但不會傳遞太多信息,因為您將實際數據和錯誤消息放在同一級別。 如果像我一樣,您更喜歡使用ResponseEntity靜態構建器,請嘗試:

@PreAuthorize("hasRole('USER')")
@GetMapping("distance/{id}")
public ResponseEntity<Distance> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    Distance distance = distanceService.getDistanceById(id);
    if (distance == null){
        throw new ResourceNotFoundException("Distance ID " + id + " Not Found");
    }

    return new ResponseEntity.ok(distance);
}

同樣,您感興趣的是一個Distance(您的代碼可能位於一個名為DistanceController的類中),因此,在未找到它時就不要強調它。

現在,關於HTTP狀態。 如果您請求/distance/<id>權限不足,則會得到拒絕訪問(禁止訪問403),與未知資源(未找到404)不同-這就是拋出ResourceNotFoundException時返回的狀態。

在此,首先檢查訪問所請求URL的權限。 如果用戶沒有足夠的權限通過身份驗證,則會收到403錯誤。 不會,您可以自由使用,它將獲得請求的資源(200),除非它不存在(404)。

我建議使用帶有RestControllerAdvice注釋的類(例如,名為GlobalExceptionHandler)來處理錯誤情況。 當distance為null時,您將需要更改getDistanceById方法以引發自定義異常。 您將需要向GlobalExceptionHandler添加一個方法來處理您的自定義異常。 然后您可以將代碼更改為以下內容:

@PreAuthorize("hasAuthority('ROLE_USER')")
@GetMapping("distance/{id}")
public ResponseEntity<Distance> getDistanceById(@PathVariable("id") Integer id) {
    log.info("getDistanceById");
    return ResponseEntity.ok(distanceService.getDistanceById(id));
}

暫無
暫無

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

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