首页 > 解决方案 > 当 REST API 中的自动绑定失败时,@ExceptionHandler 不起作用

问题描述

我有两个 REST API 的 GET POST

当方法内抛出任何异常时,异常处理程序工作正常。但是,如果我使用格式错误的 REST api uri,那么它只会显示 400 Bad Request 而不会进入异常处理程序。

例如。

如果我点击http://localhost:8080/mypojoInteger/abc,它无法将字符串解析为 Integer,因此我希望它会转到 ExceptionHandler。它不会转到异常处理程序,而是我只看到 400 Bad Request。

当在 GET/POST 方法中抛出任何异常时,它工作正常并转到异常处理程序。

例如:如果我在路径变量 http://localhost:8085/mypojoInteger/123中使用 123,它工作正常并转到异常处理程序

并将 getData 方法更改为

 @GetMapping("/mypojoInteger/{sentNumber}")
    public void getData(@PathVariable("sentNumber") Integer sentNumber) {
    throw new NumberFormatException("Exception");    
    }

注意:同样的问题也与 POST 请求有关。

  1. 得到:
   @GetMapping("/mypojoInteger/{sentNumber}")
   public void getData(@PathVariable("sentNumber") Integer sentNumber) {
   //some code    
   }
  1. 邮政:
 public void postData(@RequestBody MyPojo myPojo) {
    //some code
  }

控制器建议类:

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(NumberFormatException.class)
    protected ResponseEntity<Object> handleEntityNotFound(
            NumberFormatException ex) {

         // some logic
    }
}

当它无法将字符串绑定到 REST API uri 本身中的整数时,如何处理异常?

编辑:我的要求是我应该处理整数的溢出值,即,如果传递超过整数的最大值,它必须处理它而不是抛出 NumberFormatException 堆栈跟踪。

例如:当我传递流量值时

POJO:

public class MyPojo extends Exception {

    private String name;

    private Integer myInt;

//getters/setter
}
{
    "name":"name",
    "myInt":12378977977987879
}

如果没有 @ControllerAdvice,它只会显示 NumberFormatException StackTrace。使用 @ControllerAdvice 它只显示 400 错误请求,没有响应实体。在这种情况下,我不希望这个默认的 stacktrace/400 错误请求,但我想显示我的自定义消息。

标签: spring-bootspring-mvc

解决方案


我看到的原因是,因为您的请求本身格式错误-> 方法体永远不会被执行-因此永远不会发生异常,因为它只是为了处理方法中的错误。形成适当的请求主体而不是允许它执行任何方法以便您事先了解问题可能是更好的设计选择。


推荐阅读