【问题标题】:Exception Handling in Spring bootSpring Boot 中的异常处理
【发布时间】:2016-05-26 21:40:32
【问题描述】:

我有一个 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 并返回错误消息?

【问题讨论】:

    标签: java spring exception-handling spring-boot http-request-parameters


    【解决方案1】:

    您可以在同一控制器中或在处理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 的更多详细信息,您可以参考documentation

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2017-09-14
      • 2015-02-23
      • 2016-09-29
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多