春ブーツ私自身の検証制約エラーメッセージを返す方法

イベントは省略します:

何かが私の要求と間違って行くとき、私は自分のエラーレスポンスボディを持っている必要がありますし、私が使用しようとしています@NotEmpty、エラーメッセージを返すように制約メッセージ属性を

これは私が必要とする体を使用して、エラーメッセージを返す私のクラスです。

package c.m.nanicolina.exceptions;


import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
        ApiError apiError = new ApiError(ex.getMessage(), ex.getMessage(), 1000);
        return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
    }
}

これでCustomResponseEntityExceptionHandler私は、バリデーションエラーの場合には私自身のレスポンスボディを返すことができます。

私が今しようとしていることは、検証の制約からメッセージを取得することです。

これは、と私のコントローラであるNotEmpty制約:

package c.m.nanicolina.controllers;

import c.m.nanicolina.models.Product;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;

@RestController
public class MinimumStockController {

    @RequestMapping(value = "/minimumstock")
    public Product product(
            @RequestParam(value = "product.sku") @NotEmpty(message = "Product.sku cannot be empty") String sku,
            @RequestParam(value = "stock.branch.id") String branchID) {
        return null;
    }
}

私は例外で、私はそのメッセージを取得する方法を見つけることができませんProduct.sku cannot be emptyし、私のエラー応答でそれを示しています。

私はまた、クラスをチェックしているMissingServletRequestParameterExceptionと方法があるgetMessageデフォルトのメッセージを返しています。

Amithクマール:

はい、それは非常によく、なんとか&スプリングであることをサポートしています。あなたは春にそれを有効にするには、いくつかの設定を欠けています。

  • 使用春の@Validated検証コントローラに春を有効にするには、注釈
  • ハンドルConstraintViolationExceptionあなたにControllerAdvice失敗したすべての検証メッセージをキャッチします。
  • マークrequired=false@RequestParam、それはMissingServletRequestParameterExceptionを投げると、むしろ制約バリデーションの次のステップに移動しません。
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler
  public ResponseEntity<ApiError> handle(ConstraintViolationException exception) {
        //you will get all javax failed validation, can be more than one
        //so you can return the set of error messages or just the first message
        String errorMessage = new ArrayList<>(exception.getConstraintViolations()).get(0).getMessage();
       ApiError apiError = new ApiError(errorMessage, errorMessage, 1000);    
       return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
  }
}



@RestController
@Validated
public class MinimumStockController {

    @RequestMapping(value = "/minimumstock")
    public Product product(
            @RequestParam(value = "product.sku", required=false) @NotEmpty(message = "Product.sku cannot be empty") String sku,
            @RequestParam(value = "stock.branch.id", required=false) String branchID) {
        return null;
    }
}

注: MissingServletRequestParameterException制約の検証が要求のライフサイクルで発生する前に、それがスローされると、javaxの検証メッセージにアクセスすることはできません。

おすすめ

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