Spring Boot如何返回我自己的验证约束错误消息

时间:2018-07-13 19:27:19

标签: java validation spring-boot exception-handling query-parameters

当我的请求出现问题时,我需要有自己的错误响应正文,而我正尝试使用@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返回了默认消息。

4 个答案:

答案 0 :(得分:4)

是的,它是可行的,并且spring很好地支持了它。您只是缺少一些在春天启用它的配置。

  
      
  • 使用Spring @Validated注释使spring能够验证控制器
  •   
  • 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验证消息,因为它是在请求生命周期中进行约束验证之前抛出的。

答案 1 :(得分:0)

您应该将其放在处理程序上。

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler(value = { MissingServletRequestParameterException.class })
    public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
        String message = ex.getParameterName() + " cannot be empty";
        ApiError apiError = new ApiError(ex.getMessage(), message, 1000);
        return new ResponseEntity < ApiError > (apiError, null, HttpStatus.BAD_REQUEST);
    }
}

更新

我不知道如何获取默认消息,但是作为一种变通办法,您可以在控制器上进行验证并在参数为空的情况下引发自定义异常,然后在CustomResponseEntityExceptionHandler中进行处理。

类似以下内容:

设置required=false

@RequestMapping(value = "/minimumstock")
public Product product(@RequestParam(required = false) String sku, @RequestParam(value = "stock.branch.id") String branchID) {
    if (StringUtils.isEmpty(sku)) 
        throw YourException("Product.sku cannot be empty");

    return null;
}

答案 2 :(得分:0)

是的,有可能。这样做:

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ArgumentsErrorResponseDTO> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {

    ServiceException exception = ServiceException.wrap(ex, ErrorCode.FIELD_VALIDATION);
    BindingResult results = ex.getBindingResult();
    for (FieldError e: results.getFieldErrors()) {
        exception.addLog(e.getDefaultMessage(), e.getField());
    }
    // log details in log
    log.error("Invalid arguments exception: {}", exception.logWithDetails(), exception);
    return ResponseEntity.status(exception.getErrorCode().getHttpStatus())
            .body(ArgumentsErrorResponseDTO.builder()
                    .code(exception.getErrorCode().getCode())
                    .message(exception.getMessage())
                    .details(exception.getProperties())
                    .build());
}

答案 3 :(得分:0)

如果有帮助,我在这里找到了解决此问题的方法:https://howtodoinjava.com/spring-boot2/spring-rest-request-validation/

您必须将此方法添加到CustomResponseEntityExceptionHandler类:

 @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> details = new ArrayList<>();
        for(ObjectError error : ex.getBindingResult().getAllErrors()) {
            details.add(error.getDefaultMessage());
        }
        ErrorMessage error = new ErrorMessage(new Date(), details.toString());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }