簡體   English   中英

Spring Boot中的異常處理

[英]Exception Handling in Spring boot

我有一個具有以下端點的spring-boot應用程序:

@RequestMapping("/my-end-point")
public MyCustomObject handleProduct(
  @RequestParam(name = "productId") String productId,
  @RequestParam(name = "maxVersions", defaultValue = "1") int maxVersions,
){
   // my code
}

這應該處理以下形式的請求

/my-end-point?productId=xyz123&maxVersions=4

但是,當我指定maxVersions=3.5 ,這將引發NumberFormatException (出於明顯的原因)。 我如何優雅地處理此NumberFormatException並返回錯誤消息?

您可以在處理MethodArgumentTypeMismatchException異常的同一控制器或ControllerAdvice中定義ExceptionHandler

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public void handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
    String name = ex.getName();
    String type = ex.getRequiredType().getSimpleName();
    Object value = ex.getValue();
    String message = String.format("'%s' should be a valid '%s' and '%s' isn't", 
                                   name, type, value);

    System.out.println(message);
    // Do the graceful handling
}

如果在控制器方法自變量解析期間,Spring檢測到方法自變量類型與實際值類型之間的類型不匹配,則將引發MethodArgumentTypeMismatchException 有關如何定義ExceptionHandler更多詳細信息,請查閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM