【问题标题】:Handling exception at a controller method signature在控制器方法签名处处理异常
【发布时间】:2019-08-25 16:39:50
【问题描述】:

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

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

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

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 响应代码。我怎么做?还是有另一种方法来检查非空属性?

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

【问题讨论】:

  • "我想捕获异常并发送带有适当响应正文的 200 响应代码。" - 不要那样做。您应该返回 HTTP 错误 400(错误请求)。
  • 目前它给出了 500 响应。到目前为止,我无法控制它的行为。我什至如何发送 400 响应
  • 也许this baelung article 有帮助。
  • 如果您查看 @Turing85 附加的文章并前往第 4 节,解决方案 3 - 您会发现一个非常有用的 ControllerAdvice 示例。这是我个人使用的,建议您也这样做。

标签: java spring spring-boot http-post


【解决方案1】:

要做你想做的事,你需要使用@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,一个非常常见的异常,您的应用程序抛出的每个空指针都将由您的自定义控制器处理。

【讨论】:

  • @uneq95 很高兴为您提供帮助;D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多