@ExceptionHandler with three @Validated @RequestBody used can be well done with the calibration parameters, the following specific demo:
interface
import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import com.xx.common.core.CommonResult; import com.xx.product.input.dto.ProductDetailCollectParam; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Api (tags = "product details page Interface") @RequestMapping(value = "/product") public interface ProductDetailService { @PostMapping("/collect") @ApiOperation (value = "Favorite Interface") public CommonResult collectProduct(@RequestBody @Validated ProductDetailCollectParam productDetailCollectParam); }
Into the reference category
import javax.validation.constraints.NotBlank; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data @ApiModel (value = "product details page to the Senate") public class ProductDetailCollectParam { @NotBlank (message = "User openid not be blank") @ApiModelProperty(value = "用户openid") private String openid; @NotBlank (message = "Product id can not be null.") @ApiModelProperty(value = "商品id") private String id; }
Global catch the exception class
import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; import javax.validation.ConstraintViolationException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import com.xx.common.core.CommonResult; cn.hutool.core.util.StrUtil import; import lombok.extern.slf4j.Slf4j; @ slf4j @RestControllerAdvice public class GlobalExecptionHandler { /** * Global exception interception * @stop me * @return */ @ExceptionHandler(Exception.class) public CommonResult handler(Exception exception) { StringBuilder errMsg = new StringBuilder(); // method parameters invalid exception if(exception instanceof MethodArgumentNotValidException) { BindingResult bindResult = ((MethodArgumentNotValidException) exception).getBindingResult(); List<FieldError> fieldErrorList = bindResult.getFieldErrors(); fieldErrorList.forEach(fieldErrors -> { FieldError fieldError = fieldErrors; if (StrUtil.isNotBlank(errMsg.toString())) { errMsg.append(","); } errMsg.append(fieldError.getDefaultMessage()); } ); }else if (exception instanceof ConstraintViolationException) { // constraint violation exception } // log.error ( "anomaly:", exception); return CommonResult.failed(errMsg.toString()); }
Reference Links: https://www.cnblogs.com/cjyboy/p/11465876.html
Reference Links: https://blog.csdn.net/lzhcoder/article/details/98870852