我可以在Spring Boot API休息

发布于 2025-01-31 02:17:47 字数 1669 浏览 3 评论 0原文

这个问题让我发疯,我不知道在哪里看。

我有一个REST API,它接收@requestbody dto

public ResponseEntity<JuntaCalificadoraDTO> edit(@Valid @RequestBody JuntaCalificadoraDTO juntaCalifDTO) {
......

这是我收到的DTO,并且可以通过Java Bean验证进行验证。使用Lombok Java Bean验证生成Getter和Setters

@Data
@NoArgsConstructor
public class JuntaCalificadoraDTO extends RepresentationModel<JuntaCalificadoraDTO> {

    private Long id_process;

    @NotNull @Min(1) @Positive
    private Integer presidentJC;

    @NotNull @Min(1) @Positive
    private Integer secretaryJC;

    @NotNull @Min(1) @Positive
    private Integer representativeFuncJC;

}

可以完成工作。它不是零,最小值和正值是有效的。问题在于,当我将字母传递给变量时,它不会验证,例如:

{
    "id_process": 4455,
    "presidentJC": "dd",
    "secretaryJC": 33,
    "representativeFuncJC": 3
}

它检测到错误,而Postman返回“ 400不良请求”,但没有其他。同样,Intellij控制台没有显示任何内容,没有堆栈。

我需要捕获我认为是“ numberFormateXception”的错误,但我无法做到。而且我不知道他为什么藏它。我在@controllerAdvice类中创建了一种方法,但也没有成功。

    @ExceptionHandler (value = {NumberFormatException.class})
    public final ResponseEntity<Object> invalidNumberHandling(NumberFormatException ex) {
        
        ApiError apiError = ApiError.builder()
                .timestamp(LocalDateTime.now())
                .status(HttpStatus.BAD_REQUEST)
                .message("Number Format Exception")
                .errors(List.of("El o los parámetros de entrada no son válidos"))
                .details(ex.getMessage())
                .build();

        return new ResponseEntity<>(apiError, apiError.getStatus());

    }

感谢任何指导。对不起,我的英语不好

this problem has me crazy and I don't know where to look anymore.

I have a rest api that receives a @RequestBody DTO

public ResponseEntity<JuntaCalificadoraDTO> edit(@Valid @RequestBody JuntaCalificadoraDTO juntaCalifDTO) {
......

This is the DTO that I receive and that I validate with java bean validations. Generate getter and setters with lombok

@Data
@NoArgsConstructor
public class JuntaCalificadoraDTO extends RepresentationModel<JuntaCalificadoraDTO> {

    private Long id_process;

    @NotNull @Min(1) @Positive
    private Integer presidentJC;

    @NotNull @Min(1) @Positive
    private Integer secretaryJC;

    @NotNull @Min(1) @Positive
    private Integer representativeFuncJC;

}

Java bean validations does its job. It is valid that it is not zero, its minimum and also that it is positive. The problem is that it does not validate when I pass a letter to a variable, for example:

{
    "id_process": 4455,
    "presidentJC": "dd",
    "secretaryJC": 33,
    "representativeFuncJC": 3
}

It detects the error, and postman returns "400 Bad Request" but nothing else. Also the Intellij console doesn't show anything, no stack.

I need to catch that error which I imagine is a "NumberFormatException" but I haven't been able to. And I don't know why he hides it. I created a method in a @ControllerAdvice class but no success either.

    @ExceptionHandler (value = {NumberFormatException.class})
    public final ResponseEntity<Object> invalidNumberHandling(NumberFormatException ex) {
        
        ApiError apiError = ApiError.builder()
                .timestamp(LocalDateTime.now())
                .status(HttpStatus.BAD_REQUEST)
                .message("Number Format Exception")
                .errors(List.of("El o los parámetros de entrada no son válidos"))
                .details(ex.getMessage())
                .build();

        return new ResponseEntity<>(apiError, apiError.getStatus());

    }

I will appreciate any guidance. And sorry for my bad english

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渡你暖光 2025-02-07 02:17:47

你很近。实际上,它是InvalidFormateXception,它包裹在httpmessagenotableexpection中。

通过捕获InvalidFormateXception您可以访问失败和错误的值的字段,因此它应该足以为用户创建有意义的响应。

如果您有任何疑问,请参见此示例应用程序(Java 17) - 如果这不起作用,请让我知道您的Spring Boot版本。


@SpringBootApplication
public class SO72312634 {

    public static void main(String[] args) {
        SpringApplication.run(SO72312634.class, args);
    }

    @Controller
    static class MyController {

        @PostMapping
        public ResponseEntity<?> edit(@Valid @RequestBody JuntaCalificadoraDTO juntaCalifDTO) {
            return ResponseEntity.ok().build();
        }
    }

    @Bean
    ApplicationRunner runner() {
        return args -> new RestTemplate().exchange(RequestEntity
                    .post("http://localhost:8080")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body("""
                             {
                                "id_process": 4455,
                                "presidentJC": "ds",
                                "secretaryJC": "abc",
                                "representativeFuncJC": 3
                            }
                            """), String.class);
    }

    @ControllerAdvice
    static class ExceptionAdvice {

        @ExceptionHandler(value = InvalidFormatException.class)
        public final ResponseEntity<Object> httpMessageNotReadable(InvalidFormatException ex) {
            String failedPaths = ex.getPath().stream().map(JsonMappingException.Reference::getFieldName).collect(Collectors.joining());
            return new ResponseEntity<>("Field %s has invalid value %s ".formatted(failedPaths, ex.getValue()), HttpStatus.BAD_REQUEST);
        }
    }

    @Data
    @NoArgsConstructor
    public static class JuntaCalificadoraDTO {

        private Long id_process;

        @NotNull
        @Min(1) @Positive
        private Integer presidentJC;

        @NotNull @Min(1) @Positive
        private Integer secretaryJC;

        @NotNull @Min(1) @Positive
        private Integer representativeFuncJC;

    }

}

输出:

由:org.springframework.web.client.httpclienterrorexception $ badrequest:400:“ field Presidentjc具有无效的值DS”

You are close. It's actually an InvalidFormatException that is wrapped into a HttpMessageNotReadableException.

By catching the InvalidFormatException you have access to the field that failed and to the wrong value, so it should be enough for you create a meaningful response to the user.

See this sample application (Java 17) in case you have any doubts - if this doesn't work please let me know your Spring Boot version.


@SpringBootApplication
public class SO72312634 {

    public static void main(String[] args) {
        SpringApplication.run(SO72312634.class, args);
    }

    @Controller
    static class MyController {

        @PostMapping
        public ResponseEntity<?> edit(@Valid @RequestBody JuntaCalificadoraDTO juntaCalifDTO) {
            return ResponseEntity.ok().build();
        }
    }

    @Bean
    ApplicationRunner runner() {
        return args -> new RestTemplate().exchange(RequestEntity
                    .post("http://localhost:8080")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body("""
                             {
                                "id_process": 4455,
                                "presidentJC": "ds",
                                "secretaryJC": "abc",
                                "representativeFuncJC": 3
                            }
                            """), String.class);
    }

    @ControllerAdvice
    static class ExceptionAdvice {

        @ExceptionHandler(value = InvalidFormatException.class)
        public final ResponseEntity<Object> httpMessageNotReadable(InvalidFormatException ex) {
            String failedPaths = ex.getPath().stream().map(JsonMappingException.Reference::getFieldName).collect(Collectors.joining());
            return new ResponseEntity<>("Field %s has invalid value %s ".formatted(failedPaths, ex.getValue()), HttpStatus.BAD_REQUEST);
        }
    }

    @Data
    @NoArgsConstructor
    public static class JuntaCalificadoraDTO {

        private Long id_process;

        @NotNull
        @Min(1) @Positive
        private Integer presidentJC;

        @NotNull @Min(1) @Positive
        private Integer secretaryJC;

        @NotNull @Min(1) @Positive
        private Integer representativeFuncJC;

    }

}

Output:

Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : "Field presidentJC has invalid value ds "

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文