弹簧静止误差处理@ControllerAdvice/@Valid

2022-09-02 09:04:22

我在使用@ControllerAdvice时遇到问题,并在REST控制器中一起@Valid注释。

我有一个休息控制器声明如下:

@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 类会正确处理该异常。

但是,当向控制器提交无效请求时,RestErrorHandler 不会捕获验证程序引发的异常,并且我收到 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注释。

我的上下文.xml非常简单,只包含一个控制器扫描仪,并启用mvc:注释驱动

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

有没有人知道如何在REST控制器中制作工作@ControllerAdvice和@Valid注释?

提前致谢。安东尼奥


答案 1

你走在正确的轨道上,但你需要覆盖句柄MethodArgumentNotValid()而不是方法,例如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:

对带有 @Valid 注释的参数进行验证失败时要引发的异常。

换句话说,当验证失败时,将引发 a。它由 提供的方法处理,如果需要自定义实现,则需要重写该方法。MethodArgumentNotValidExceptionhandleMethodArgumentNotValid()ResponseEntityExceptionHandler


答案 2

更好的返回消息格式:

@ControllerAdvice
public class MyControllerAdvice extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex,
        HttpHeaders headers,
        HttpStatus status,
        WebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
            .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
            .collect(Collectors.toList());

    return handleExceptionInternal(ex, "Method argument not valid, fieldErrors:" + fieldErrors ,new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }

}

推荐