2017-11-15 14 views
0

春のブートレストにはまったく新しいもので、サービスを使用するクライアントへの応答を処理する方法と方法については質問があります。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はそれのコンストラクタに文字列を設定し、単純なクラスです:現在、私は、データベースクエリで発見されていないレコードの場合を処理するため、次のコントローラのコードを持っています。

これが最善のアプローチですか? ControllerAdviceベースのクラスはより良いaproachですか?上記のコードは、許可なく呼び出されたときに403の応答を送信するため、この質問をしてください。それがどのように起こっているのか、それがNOT FOUND状態で使用できるのかを理解したいと思います。

+0

@PreAuthorizeのため、403はSpringフレームワークによって送信されます。 Not foundの場合、例外ハンドラアドバイスを使用してこれを行うことができます – pvpkiran

答えて

0

「リソースが見つかりません」はよく知られている使用例で、ResponseEntityまたはControllerAdviceで「気にする」必要はありません。単にResourceNotFoundExceptionを使用することができます。戻り値の型としてResponseEntity<?>を宣言

@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静的ビルダーを使用する場合:

再び
@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); 
} 

、あなたが興味を持っていることの距離(あなたのコードは、おそらくDistanceControllerというクラスに立つ)で、それではとき強調しないようにしましょうそれは見つからない。

ここで、HTTPステータスについてです。 特権が不十分である/distance/<id>を要求すると、不明なリソース(404 Not Found)と同じではないアクセス拒否(403 Forbidden)が発生します。これはResourceNotFoundExceptionがスローされたときのステータスです。

ここでは、要求されたURLにアクセスするためのアクセス許可が最初に確認されます。不十分な権限でユーザーが認証されると、403エラーが発生します。それは存在しない限り、自由に行かなくても、要求されたリソース(200)を取得します(404)。

0

エラーケースを処理するために、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)); 
} 
関連する問題