简体   繁体   English

@Valid不适用于jax rs和springboot

[英]@Valid is not working with jax rs and springboot

I am getting NotFoundException while trying to implement custom exception handling in spring-boot rest application. 我在尝试在spring-boot rest应用程序中实现自定义异常处理时遇到了NotFoundException

The code was working fine when I was using MVC (using @ControllerAdvice ) annotations but not sure when I am sending a data which is violating the constraint mentioned in entity(pojo class) it is throwing only NotFoundException (for all validation failure) but not the MethodViolationException or ConstraintViolationException 当我使用MVC(使用@ControllerAdvice )批注时,代码运行良好,但是不确定当我发送违反实体(pojo类)中提到的约束的数据时,它仅抛出NotFoundException (对于所有验证失败),但没有抛出MethodViolationExceptionConstraintViolationException

I am not able to send the message for that particular violation. 我无法针对该特定违规发送消息。

Not sure where I am making this mistake. 不知道我在哪里犯这个错误。 Please help 请帮忙

Code: 码:

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

// Rest of the code

} 

POJO: POJO:

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

} }

Exception Handler: 异常处理程序:

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

**UPDATE 1 **更新1

If I enable the send_error_in_response i am getting the message for this but not sure why my custom exception handler is not able to catch this exception and only throwing NotFoundException 如果启用send_error_in_response,我将收到此消息,但不确定为什么我的自定义异常处理程序无法捕获此异常,而仅引发NotFoundException

Try Handling Exception Using: 尝试使用以下方法处理异常:

@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);
  }

For more information you might want to refer http://www.springboottutorial.com/spring-boot-validation-for-rest-services 有关更多信息,您可能需要参考http://www.springboottutorial.com/spring-boot-validation-for-rest-services

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM