当前位置: 首页 > 面试题库 >

自定义验证器消息:ConstraintValidator的实现中引发异常导致UnexpectedException

何宏博
2023-03-14
问题内容

所以,我有自定义的验证,当我设定return值,false那么它的工作原理-

import com.vhealth.api.service.UserService;
import com.vhealth.api.utils.exceptions.InvalidPayloadException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;


public class UserNameUniqueValidator implements ConstraintValidator<UserNameUnique, String> {
    @Autowired
    UserService userService;

    @Override
    public void initialize(UserNameUnique constraintAnnotation) {
    }

    @Override
    public boolean isValid(String userName, ConstraintValidatorContext context) {
        if (userService.findByUserName(userName) != null) {
            throw new InvalidPayloadException("Creating user requires unique userName new");
            //return false;
        }
        return true;
    }
}

但是,当我尝试在该部分中引发异常时,出现错误,该问题是由我的自定义异常引起的:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ValidationException: Unexpected exception during isValid call
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:932)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:134)
    at com.vhealth.api.controller.ApiUserControllerTest.shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName(ApiUserControllerTest.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: javax.validation.ValidationException: Unexpected exception during isValid call
    at org.hibernate.validator.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:281)
    at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:153)
    at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:117)
    at org.hibernate.validator.metadata.MetaConstraint.validateConstraint(MetaConstraint.java:84)
    at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:452)
    at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:397)
    at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:361)
    at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:313)
    at org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:139)
    at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:102)
    at org.springframework.validation.DataBinder.validate(DataBinder.java:772)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.validate(RequestResponseBodyMethodProcessor.java:115)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:101)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
    ... 68 more
Caused by: com.vhealth.api.utils.exceptions.InvalidPayloadException: Creating user requires unique userName new
    at com.vhealth.api.utils.validators.UserNameUniqueValidator.isValid(UserNameUniqueValidator.java:22)
    at com.vhealth.api.utils.validators.UserNameUniqueValidator.isValid(UserNameUniqueValidator.java:11)
    at org.hibernate.validator.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:278)
    ... 90 more

放置了例外 @Controller ExceptionResolover

    @ExceptionHandler(InvalidPayloadException.class)
public ResponseEntity handleEmptyFieldException(InvalidPayloadException ex) {
    return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
}

编辑:抛出InvalidPayloadException异常UserNameUniqueValidator返回自定义消息,所以我避免BindingResult在主控制器中使用从中提取默认消息validaor


问题答案:

如果要显示自定义消息,请尝试以下代码。

@Override
public boolean isValid(String userName, ConstraintValidatorContext context) {
    if (userService.findByUserName(userName) != null) {
        context.disableDefaultConstraintViolation();
        context
            .buildConstraintViolationWithTemplate("User " + userName + "already exists!")
            .addConstraintViolation();
        return false;
    }
    return true;
}


 类似资料:
  • 我正在将Laravel-5.8与Vue一起使用。js。我的问题是如何在Vee Validate库中显示规则的自定义错误消息。“required”规则的自定义消息没有显示,而是显示为:“first_name字段是必需的。”预期的消息是“请输入名字。” 下面的代码在应用程序中。js 这是我的HTML组件代码。 下面是我的JS脚本代码 我遗漏了什么吗?

  • Spring靴2.0.3。发布,javax。验证2.0.1。最后一个选项被使用。 我需要验证进入控制器的请求: 这叫做服务: 将对象保存到MongoRepository方法

  • 我正在尝试在laravel中编写用于验证的自定义消息。我在网上查过,看到一些帖子,其他人通过添加一个受保护的函数来解决同样的问题。我还向代码中添加了该函数,但它不起作用。这是我的代码这是myFormController.php: 公共函数请求(注册请求$request){$validated=$request- 这是RegistrationRequest.php: 使用Illumb\Contrac

  • 我使用的是jboss KeyCloak1.5最终版本。我开发了与keycloak属性和我的用户企业数据库接口的自定义用户联邦提供程序。 我的需要是发送到用户登录界面自定义的错误消息,基于特定的特定错误与我的遗留用户数据库。

  • 我正在努力裁剪javax。验证。ConstraintValidator和javax。验证。根据我的需要限制ValidatorContext。我从格式错误的请求正文收到的响应消息始终采用以下形状: <代码> 此消息也以500而不是400错误请求的形式返回。我无法获得工作到解决方案来执行以下操作: 仅包括<代码> 我有以下代码: 向上面的代码发送格式错误的有效负载将导致如下消息: 我希望能够收到以下信

  • 我用Spring5反应式编写了一个自定义异常 我把这个叫做服务: 但是当我到达这个页面时,会抛出一个异常,但它不是404,而是一个空指针异常和一个错误500页面,但有正确的消息? AddressNotFound永远不会抛出,只有Nullpointer异常,但会抛出我的自定义消息???你能帮帮我吗? 这是我的控制器: 谢谢