gpt4 book ai didi

java - 响应实体异常处理程序 : handleMethodArgumentNotValid Not Intercepted

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:20 25 4
gpt4 key购买 nike

我的 Controller 有以下方法:

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void save(@RequestBody @Valid final User resource) {
createInternal(resource);
}

由于资源参数之前的 @Valid,我希望当我将 NULL 传递到实体的 @Column 上的 nullable=false 时,它会被以下异常处理程序拦截,

@Override
protected final ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException e,
final HttpHeaders headers,
final HttpStatus status,
final WebRequest request) {
log.info("Bad Request: {}", ex.getMessage());
log.debug("Bad Request: ", ex);

...

return handleExceptionInternal(e, dto, headers, HttpStatus.BAD_REQUEST, request);
}

但看来我只能这样处理:

@ExceptionHandler(value = { ConstraintViolationException.class,  
DataIntegrityViolationException.class })
public final ResponseEntity<Object> handleBadRequest(final RuntimeException e,
final WebRequest request) {
...
return handleExceptionInternal(ex, apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}

为什么handleMethodArgumentNotValid异常处理程序没有像它应该的那样拾取它?

最佳答案

在“handleMethodArgumentNotValid”有机会触发之前,DefaultHandlerExceptionResolver 会处理此问题

或者如果你想处理声明,@ExceptionHandler(MethodArgumentNotValidException.class)

An @RequestBody method parameter can be annotated with @Valid, in which case it will be validated using the configured Validator instance. When using the MVC namespace or the MVC Java config, a JSR-303 validator is configured automatically assuming a JSR-303 implementation is available on the classpath.

Just like with @ModelAttribute parameters, an Errors argument can be used to examine the errors. If such an argument is not declared, a MethodArgumentNotValidException will be raised. The exception is handled in the DefaultHandlerExceptionResolver, which sends a 400 error back to the client. Before your 'handleMethodArgumentNotValid' has a chance to fire, this is handndf

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody

关于java - 响应实体异常处理程序 : handleMethodArgumentNotValid Not Intercepted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40670447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com