将特定的约束验证器映射到泽西州的特定ContraintViolationException [英] Mapping specific constraint validator to specific ContraintViolationException in Jersey

查看:175
本文介绍了将特定的约束验证器映射到泽西州的特定ContraintViolationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义验证器并将其映射到特定的constraintViolationException。原因是我想为不同的约束创建不同的自定义异常。例如,如果在数据库中找不到用户,则会触发找不到的violationException,而如果用户具有无效的用户名,则会执行错误的responseException violationException。

$ p $ @Retention(RUNTIME)
@Target({FIELD,METHOD})
@Constraint(validatedBy = UserNotValidValidator.class)
public @interface UserIsValid {...}

映射到

  public class ConstraintExceptionMapper实现
ExceptionMapper< ConstraintViolationException> {
public Response toResponse(ConstraintViolationException e){...}
}

更具体地说,问题是bean hibernate验证器是否支持多个约束异常映射器。

解决方案

异常映射器是一个概念JAX-RS不是Bean验证。您应该为 ConstraintViolationException 创建一个异常映射器,并根据给定违例异常中包含的违规情况创建不同的响应。例如。你可以通过`ConstraintViolation.getConstraintDescriptor()。getAnnotation()。annotationType()。
来检查违反的约束类型

I am trying to create a custom validator and mapped it into a specific constraintViolationException. The reason is I want to create different custom exception for different constraint. For example, if a user is not found in the database, a not found violationException is triggered, while if the user has invalid username, a bad response violationException will be executed instead.

@Retention(RUNTIME)
@Target({ FIELD, METHOD })
@Constraint(validatedBy = UserNotValidValidator.class)
public @interface UserIsValid { ... }

mapped into

public class ConstraintExceptionMapper implements
    ExceptionMapper<ConstraintViolationException> {
   public Response toResponse(ConstraintViolationException e) { ... }
}

To be more specific, the question is whether bean hibernate validator supports multiple constraint exception mapper.

解决方案

Exception mappers are a concept of JAX-RS not of Bean Validation. You should create one exception mapper for ConstraintViolationException and have it create different responses based on the violations contained within a given violation exception. E.g. you can examine the violated constraint type via `ConstraintViolation.getConstraintDescriptor().getAnnotation().annotationType().

这篇关于将特定的约束验证器映射到泽西州的特定ContraintViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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