Spring启动时的异常处理

Nik*_*Nik 1 java spring exception-handling http-request-parameters 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
}
Run Code Online (Sandbox Code Playgroud)

这应该处理表单的请求

/my-end-point?productId=xyz123&maxVersions=4
Run Code Online (Sandbox Code Playgroud)

但是,当我指定时maxVersions=3.5,这会抛出NumberFormatException(显而易见的原因).我怎样才能优雅地处理这个NumberFormatException并返回错误信息?

Ali*_*ani 5

您可以ExceptionHandler在同一个控制器或ControllerAdvice处理MethodArgumentTypeMismatchException异常的控制器中定义:

@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
}
Run Code Online (Sandbox Code Playgroud)

如果在控制器方法参数解析期间,Spring检测到方法参数类型和实际值类型之间的类型不匹配,则会引发一个MethodArgumentTypeMismatchException.有关如何定义的更多详细信息ExceptionHandler,请参阅文档.