简体   繁体   English

Spring Boot中的异常处理

[英]Exception Handling in Spring boot

I have a spring-boot application which has the following end point: 我有一个具有以下端点的spring-boot应用程序:

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

This should handle requests of the form 这应该处理以下形式的请求

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

However, when I specify maxVersions=3.5 , this throws NumberFormatException (for obvious reason). 但是,当我指定maxVersions=3.5 ,这将引发NumberFormatException (出于明显的原因)。 How can I gracefully handle this NumberFormatException and return an error message? 我如何优雅地处理此NumberFormatException并返回错误消息?

You can define an ExceptionHandler in the same controller or in a ControllerAdvice that handles the MethodArgumentTypeMismatchException exception: 您可以在处理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
}

If during controller method argument resolution, Spring detects a type mismatch between the method argument type and actual value type, it would raise an MethodArgumentTypeMismatchException . 如果在控制器方法自变量解析期间,Spring检测到方法自变量类型与实际值类型之间的类型不匹配,则将引发MethodArgumentTypeMismatchException For more details on how to define an ExceptionHandler , you can consult the documentation . 有关如何定义ExceptionHandler更多详细信息,请查阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM