春の残りの部分とグローバルな例外ハンドラでは汎用的な例外クラスのハンドラを持っていることをお勧めますか?

Dhruv Kapatel:

私が使用してグローバル例外ハンドラを作成するには、いくつかの記事を参照して@ControllerAdvice、スプリングを使用して、私のREST APIプロジェクトのために。この目的は、発生した例外の場合は、クライアントに適切なフォーマットされた応答を送信することです。いくつかの記事では、彼らは追加されているThrowableか、Exceptionグローバルな例外ハンドラインチ 私はそれがで置き換える必要がありRunTimeException、実行時に発生したこのブロックは、例外のためであると?

例外ハンドラのコード:

@ControllerAdvice
public class GlobalExceptionHandler{

    @ExceptionHandler(NoDataFoundException.class)
    @ResponseStatus(code=HttpStatus.NOT_FOUND)
    public ResponseEntity<ErrorResponse> handle(NoDataFoundException ex){
        ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(), HttpStatus.NOT_FOUND.value());
        ResponseEntity<ErrorResponse> response = new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
        return response;
    }
    ..... more methods to handle custom exceptions

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<ErrorResponse> handle(Exception ex){
        ErrorResponse errorResponse = new ErrorResponse("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR.value());
        ResponseEntity<ErrorResponse> response = new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        return response;
    }
}

ErrorResponseコード:

public class ErrorResponse {

    private String message;
    private int statusCode;

    public ErrorResponse(String message, int statusCode) {
        super();
        this.message = message;
        this.statusCode = statusCode;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public int getStatusCode() {
        return statusCode;
    }
    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
}  

参考文献:

  1. https://dzone.com/articles/exception-handling-in-spring-boot-rest-web-service
  2. https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-2-rest-service-exception-handling
davidxxx:

このブロックは例外が実行時に発生したためであると私はのRuntimeExceptionに置き換えるべきか?

あなたが任意の例外がスローされ、決してあなたのコンポーネントまたはより入力された例外を除いてすべての例外ハンドラによって処理捕まえることを確認するためにException、あなたはのためのハンドラを持っている必要がありますException
ハンドラは、RuntimeExceptionチェック例外は実行時にも、あなたのハイレベルのコンポーネントのメソッド宣言が指定した場合にスローされますので、十分ではありませんthrows Exceptionthrows "any checked exception"、チェック例外は、クライアントまたはここでデフォルトの動作を適用するコンテナまで増殖させることができました。
例えば、このような状況が起こることを作ることができ、この残りのコントローラメソッドの宣言を想像してみてください。

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Foo> getOne(@PathVariable long id) throws Exception {
       // ....           
}

そして、このデフォルトの春の動作をオーバーライドするには、ハンドラを追加することになるでしょうException
もちろん、それだけのためのハンドラを宣言することを意味するわけではないException方法ですが、あなたがいない特定の処理をし、一般的な取り扱いは大丈夫であることのために、いくつかの例外を有することができます。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=218754&siteId=1