我有一个具有以下端点的 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
并返回错误消息?
最佳答案
您可以在同一 Controller 或处理 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
}
如果在 Controller 方法参数解析期间,Spring 检测到方法参数类型和实际值类型之间的类型不匹配,它将引发 MethodArgumentTypeMismatchException
。有关如何定义 ExceptionHandler
的更多详细信息,您可以引用 documentation .
关于java - Spring Boot 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37471467/