如何在spring boot中捕获客户端参数错误的“请求处理失败”?

Ter*_*ran 5 java web spring-boot

DateTimeFormatterRegistrar在我的班级中注册了一个WebMvcConfigurer这样的实现:

@Override
public void addFormatters(FormatterRegistry registry) {
    DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
    registrar.setUseIsoFormat(true);
    registrar.registerFormatters(registry);
}
Run Code Online (Sandbox Code Playgroud)

在其余控制器中,我尝试将客户端GET参数解析为一个对象:

@GetMapping("/api/url/path")
public APIResponse getPersonAttendList(@Valid SampleVO vo){}
Run Code Online (Sandbox Code Playgroud)

SampleVO包括字段LocalDateTime time。如果客户端提供了错误的time参数格式,绑定将失败。服务器将返回 500,并像这样打印一些日志:

>ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] 175 - Servlet.service() for
servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; 
nested exception is java.time.format.DateTimeParseException
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何捕获此异常并将 400 返回给客户端?它似乎ControllerAdvice不起作用。

diz*_*mac 0

您应该能够使用“try{}、catch(){} 和finally{}”捕获此内容。您可以尝试该代码,然后捕获异常,然后向客户端返回 400 错误。

try {
    //your code
} catch (java.time.format.DateTimeParseException e) {
    //Return 400 here
} finally {
    //Other code here
}

Run Code Online (Sandbox Code Playgroud)