如何避免Spring启动API中的NumberFormatException



我有一个Spring boot Get API,它返回给定用户id的'User'对象。

@GetMapping( path = "/users/{userId}")
public ResponseEntity<User> getUser(
@PathVariable( userId )
Long id) throws CustomException {
//retuen user object
}

当有人将字符串值作为userId传递给端点时,这会返回'NumberFormatException'。它提供了在系统端使用的userId类型的概念。是否有可能,我可以返回一个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);
}
}

或者您可以查看此链接以获取更多信息spring-rest-error-handling-example

您需要使用@Validated注释验证输入。请按以下连结了解详情:https://howtodoinjava.com/spring-rest/request-body-parameter-validation/

最新更新