java - 处理 Controller 方法签名处的异常

标签 java spring spring-boot http-post

我有一个 POST 请求,其请求正文包含多个参数。在服务器端,请求正文被映射到 POJO。

如果我不发送任何请求正文,服务器会抛出错误。当我使用注释 @RequestBody(required = false) 时,请求正文将映射到 null 对象。我可以验证它并发送适当的响应。

但在这种情况下,当我在请求正文中发送一个空的 json - { } 时,它会映射到一个 not null 对象,其所有属性设置为无效的。没什么意外的。所有属性都必须为非空,因此我设置了一个属性 - @NotNull(从 org.springframework.lang.NonNull 导入)。现在,如果我发送一个空的 json { },我会收到 500 响应,但异常(exception)情况如下。

2019-08-25 21:49:21.921 ERROR 28538 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class package.model.Model]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `package.model.Model`, problem: someAttribute is marked non-null but is null
 at [Source: (PushbackInputStream); line: 3, column: 1]] with root cause

java.lang.NullPointerException: someAttribute is marked non-null but is null

我想捕获异常并发送带有适当响应正文的 200 响应代码。我怎么做?或者还有另一种方法来检查非空属性吗?

基本上我希望请求正文属性必须具有所有属性,否则我想返回自定义构建的错误响应。

最佳答案

要做你想做的事,你需要使用@ControllerAdvice。它的工作原理就像“观看”您的应用程序。

@ControllerAdvice
public class CustomizedExceptionHandler  {

    @ExceptionHandler(NotFoundException.class) // change here for your exception.
    public final ResponseEntity<ErrorDetails> handleUserNotFoundException(NotFoundException ex, WebRequest request) {
        ErrorDetails errorDetails = ErrorDetails.builder()
                .timestamp(new Date())
                .message(ex.getMessage())
                .details(request.getDescription(false))
                .build();
        return new ResponseEntity<>(errorDetails, HttpStatus.FORBIDDEN); // you can return whatever you want.
    }

}

PS:请注意,您的异常是 NullPointerException,这是一种非常常见的异常,您的应用程序抛出的每个空指针都将由您的自定义 Controller 处理。

关于java - 处理 Controller 方法签名处的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57647861/

相关文章:

java - Spring 安全: How I make to follow a link after logging and not going to the homepage

java - 在 Java 中,使用 Poll 方法的 Azure 动态刷新不适用于 Spring Boot 3.x.x

java - @EntityScan 和 @ComponentScan 之间的区别

java - o.s.web.servlet.PageNotFound - 没有映射 GET/WEB-INF/views/welcome.jsp

java - 无法为其 ID 和值每次选择时都会更改的 Web 元素单击输入文本

java - 在 HSQLDB 数据库中存储 UUID

JAVA基于文本的迷宫游戏

java - 如何使用 bean 定义对象在运行时生成/创建新的 spring bean?

java - 使用 Hibernate/Spring/Maven/MySQL 测试运行后防止数据被删除

java - 使用 jUnit 测试 Spring Restful Web 服务