gpt4 book ai didi

java - Spring Rest ErrorHandling @ControllerAdvice/@Valid

转载 作者:IT老高 更新时间:2023-10-28 13:58:59 27 4
gpt4 key购买 nike

在 REST Controller 中同时使用 @ControllerAdvice@Valid 注释时遇到问题。

我有一个休息 Controller 声明如下:

@Controller
public class RestExample {

...

/**
* <XmlRequestUser><username>user1</username><password>password</password><name>Name</name><surname>Surname</surname></XmlRequestUser>
* curl -d "@restAddRequest.xml" -H "Content-Type:text/xml" http://localhost:8080/SpringExamples/servlets/rest/add
*/
@RequestMapping(value="rest/add", method=RequestMethod.POST)
public @ResponseBody String add(@Valid @RequestBody XmlRequestUser xmlUser) {
User user = new User();
user.setUsername(xmlUser.getUsername());
user.setPassword(xmlUser.getPassword());
user.setName(xmlUser.getName());
user.setSurname(xmlUser.getSurname());

// add user to the database
StaticData.users.put(xmlUser.getUsername(), user);
LOG.info("added user " + xmlUser.getUsername());

return "added user " + user.getUsername();
}
}

还有一个 ErrorHandler 类:

@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {

private static Logger LOG = Logger.getLogger(RestErrorHandler.class);


@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Object> handleException(final RuntimeException e, WebRequest request) {
LOG.error(e);

String bodyOfResponse = e.getMessage();
return handleExceptionInternal(e, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}

问题是,如果我在 RestExample.add 方法中添加 "throw new RuntimeException",那么 RestErrorHandler 会正确处理异常强>类。

但是,当将无效请求 curl 到 Controller 时,RestErrorHandler 不会捕获 validator 抛出的异常,并且我会收到 400 BadRequest 响应。 (对于无效请求,我的意思是未指定用户名的 xml 请求)

请注意,XmlRequestUser 类是由插件 maven-jaxb2-plugin 自动生成的+ krasa-jaxb-tools (pom.xml):

<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>src/main/xsd</schemaDirectory>
<schemaIncludes>
<include>*.xsd</include>
</schemaIncludes>
<args>
<arg>-XJsr303Annotations</arg>
<arg>-XJsr303Annotations:targetNamespace=http://www.foo.com/bar</arg>
</args>
<plugins>
<plugin>
<groupId>com.github.krasa</groupId>
<artifactId>krasa-jaxb-tools</artifactId>
<version>${krasa-jaxb-tools.version}</version>
</plugin>
</plugins>
</configuration>
</plugin>

生成的类在用户名和密码字段上有正确的@NotNull 注释。

我的 context.xml 非常简单,只包含一个 Controller 扫描器并启用 mvc:annotation-driven

<context:component-scan base-package="com.aa.rest" />
<mvc:annotation-driven />

有人知道如何在 REST Controller 中同时使用 @ControllerAdvice 和 @Valid 注释吗?

提前致谢。安东尼奥

最佳答案

您在正确的轨道上,但您需要覆盖 handleMethodArgumentNotValid()而不是 handleException() 方法,例如

@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException exception,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {

LOG.error(exception);
String bodyOfResponse = exception.getMessage();
return new ResponseEntity(errorMessage, headers, status);
}
}

来自 MethodArgumentNotValidException 的 JavaDoc :

Exception to be thrown when validation on an argument annotated with @Valid fails.

换句话说,当验证失败时会抛出一个MethodArgumentNotValidException。它由 ResponseEntityExceptionHandler 提供的 handleMethodArgumentNotValid() 方法处理,如果您想要自定义实现,则需要覆盖该方法。

关于java - Spring Rest ErrorHandling @ControllerAdvice/@Valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16651160/

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