![](/img/trans.png)
[英]Spring Exception handling with @ControllerAdvice provides centralized control but we have to add all throws exception in method signature
[英]Handling exception at a controller method signature
我有一個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
響應代碼。 我怎么做? 還是有另一種方法檢查非null屬性?
基本上,我希望請求主體屬性必須具有所有屬性,否則,我想返回一個自定義的錯誤響應。
要執行您想要的操作,您需要使用@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
,這是一個非常常見的異常,您的應用程序引發的每個null指針都將由您的自定義控制器處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.