Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何避免Spring boot API中的NumberFormatException_Java_Spring_Spring Boot - Fatal编程技术网

Java 如何避免Spring boot API中的NumberFormatException

Java 如何避免Spring boot API中的NumberFormatException,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个SpringBootGetAPI,它为给定的用户id返回一个“User”对象 @GetMapping( path = "/users/{userId}") public ResponseEntity<User> getUser( @PathVariable( userId ) Long id) throws CustomException { //retuen user object } @Ge

我有一个SpringBootGetAPI,它为给定的用户id返回一个“User”对象

@GetMapping( path = "/users/{userId}")
public ResponseEntity<User> getUser(
        @PathVariable( userId )
                Long id) throws CustomException {
      //retuen user object
}
@GetMapping(path=“/users/{userId}”)
公共响应getUser(
@路径变量(用户ID)
长id)引发自定义异常{
//转发用户对象
}
当有人将字符串值作为用户ID传递给端点时,将返回“NumberFormatException”。它给出了系统端使用的用户ID类型的概念。是否有可能返回CustomException而不是“NumberFormatException”

一个选项是对userId使用类型String,然后尝试在方法内部将其转换为Long。
除此之外,有没有更好的方法来解决Spring Boot的内置最终版本的这个问题?

是的,您可以通过创建一个异常建议类来处理运行时异常

例如,要处理异常,必须执行以下操作:-

1-创建自定义类以将其用作异常响应类

public class ExceptionResponse {

    private String message;

    public ExceptionResponse(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
2-创建一个异常处理程序类来处理抛出的异常,并添加要处理的异常

@RestControllerAdvice
public class ExceptionCatcher {

    @ExceptionHandler(NumberFormatException.class)
    public ResponseEntity<ExceptionResponse> numberFormatExceptionHandler(NumberFormatException exception) {
        ExceptionResponse response = new ExceptionResponse(exception.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }
}
@RestControllerAdvice
公共类例外观察者{
@ExceptionHandler(NumberFormatException.class)
公共响应属性NumberFormatException处理程序(NumberFormatException异常){
ExceptionResponse=新的ExceptionResponse(exception.getMessage());
返回ResponseEntity.status(HttpStatus.BAD_请求).body(响应);
}
}

或者您可以查看此链接以获取更多信息

您需要使用@Validated注解验证输入。 有关更多详细信息,请点击以下链接:

为什么需要CustomException而不是更明确的NumberFormatException?由于安全问题,我不想让其他人知道,我使用的是long for UserId谢谢,这在我的场景中非常有效