【问题标题】:@Valid is not working with jax rs and springboot@Valid 不适用于 jax rs 和 spring boot
【发布时间】:2018-12-28 09:03:19
【问题描述】:

我在尝试在 spring-boot rest 应用程序中实现自定义异常处理时收到NotFoundException

当我使用 MVC(使用 @ControllerAdvice)注释时,代码运行良好,但不确定何时发送违反实体(pojo 类)中提到的约束的数据,它只抛出 NotFoundException(对于所有验证失败)但不是MethodViolationExceptionConstraintViolationException

我无法针对该特定违规行为发送消息。

不知道我在哪里犯了这个错误。请帮忙

代码:

@POST
@Path("/customers/add") 
public Response addCustomer(@Valid customer cust) 
{

// Rest of the code

} 

POJO:

@Entity
@Table(name="cust")
public class Customer
{
  @NotNull
  @Size(min=1,max=50,message ="invalid name") 
  String name;

}

异常处理程序:

@Provider
public class CustomHandler implements ExceptionMapper<Exception>
{
 public Response toResponse(Exception ex) 
 {
  if(ex instanceOf ConstraintViolationException) 
  {
    Do something
  } 
} 

**更新 1

如果我启用了 send_error_in_response,我会收到此消息,但不确定为什么我的自定义异常处理程序无法捕获此异常而只会抛出 NotFoundException

【问题讨论】:

  • 阅读 Jersey 文档中的 Bean Validation chapter
  • 您是否收到所有错误代码的 404,或者只是 bean 验证错误?
  • @Paul Samsotha 是的,现在我正在测试只是为了验证并得到这个 404 错误。在我明确抛出异常的地方,我以预期的格式得到它作为响应,但不是因为任何验证错误
  • “但不确定为什么我的自定义异常处理程序无法捕获此异常” - 这是因为 Jersey 已经有 a mapper。我认为你因为this (but not sure) 而找不到
  • 我为 ConstraintViolationException 添加了一个单独的处理程序,解决了我的问题

标签: java rest spring-boot jersey jax-rs


【解决方案1】:

尝试使用以下方法处理异常:

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(StudentNotFoundException)
  public final ResponseEntity<ErrorDetails> handleUserNotFoundException(StudentNotFoundException ex, WebRequest request) {
    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
        request.getDescription(false));
    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
  }

有关更多信息,您可能需要参考http://www.springboottutorial.com/spring-boot-validation-for-rest-services

【讨论】:

  • 当我使用 @ControllerAdvice 时它可以工作,但当我尝试使用球衣实现时它不起作用。
猜你喜欢
  • 2016-03-20
  • 1970-01-01
  • 2014-12-20
  • 2017-11-28
  • 2021-03-02
  • 2014-04-15
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多