Spring Boot如何返回我自己的验证约束错误消息 [英] Spring Boot how to return my own validation constraint error messages

查看:81
本文介绍了Spring Boot如何返回我自己的验证约束错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的请求出现问题时,我需要拥有自己的错误响应正文,而我试图使用 @NotEmpty 约束消息属性来返回错误消息,

I need to have my own error response body when something goes wrong with my request and I am trying to use the @NotEmpty constraint message attribute to return the error message,

这是我的类,它使用所需的正文返回错误消息:

This is my class that returns the error message using the body that I need:

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 ,我可以在验证错误的情况下返回自己的响应正文.

With this CustomResponseEntityExceptionHandler I can return my own response body in case of validation errors.

我现在正在尝试从验证约束中获取消息.

What I am trying now is to get the message from the validation constraints.

这是我的控制器,具有 NotEmpty 约束:

This is my controller with the NotEmpty constraint:

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不能为空并在我的错误响应中显示该消息.

In my exception, I can't find a way to get that message Product.sku cannot be empty and show it in my error response.

我还检查了类 MissingServletRequestParameterException ,并且有方法 getMessage 返回默认消息.

I have also checked the class MissingServletRequestParameterException and there is the method getMessage which is returning the default message.

推荐答案

是可以的&春天很好地支持了它.您只是缺少一些在春天启用它的配置.

Yes it is doable & spring very well supports it. You are just missing some configuration to enable it in spring.

  • 使用Spring @Validated 批注使spring能够验证控制器
  • ControllerAdvice 中处理 ConstraintViolationException ,以捕获所有失败的验证消息.
  • @RequestParam
  • @RequestParam 中标记 required = false ,因此它不会引发MissingServletRequestParameterException而是进入约束验证的下一步.
  • Use Spring@Validated annotation to enable spring to validate controller
  • Handle ConstraintViolationException in your ControllerAdvice to catch all failed validation messages.
  • Mark required=false in @RequestParam, so it will not throw MissingServletRequestParameterException and rather move to next step of constraint validation.

@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验证消息,因为它是在请求生命周期中进行约束验证之前抛出的.

NOTE: MissingServletRequestParameterException won't have access to javax validation messages, as it is thrown before constraint validation occurs in the request lifecycle.

这篇关于Spring Boot如何返回我自己的验证约束错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆