简体   繁体   English

Spring JSON 解析错误后启动人类可读错误消息

[英]Spring Boot human readable error messages after JSON parsing error

I have a REST API written using Spring Boot.我有一个 REST API 使用 Spring 引导编写。 Now I would like to to enhance error handling.现在我想加强错误处理。 If user sends either not valid JSON or JSON which can not me deserialized to my DTO I would to inform user what exactly was wrong, eg unexpected property name, type etc. Still I don't want to expose any information about the implementation (eg stacktrace, class names).如果用户发送无效的 JSON 或 JSON 无法反序列化到我的 DTO,我会通知用户究竟出了什么问题,例如意外的属性名称、类型等。我仍然不想公开有关实现的任何信息(例如堆栈跟踪,class 名称)。

Default Spring implementation returns默认 Spring 实现返回

InvalidFormatException: Cannot deserialize value of type `java.lang.Integer` from String \"aaa\": not a valid Integer value\n at [Source: (PushbackInputStream); line: 10, column: 19]
 (through reference chain: com.yell.statementofwork.model.StatementOfWorkCompletionDtoSe[\"purchasedProducts\"]->java.util.ArrayList[0]->com.yell.statementofwork.model.PurchasedProductDtoSe[\"quantity\"])",

which is almost good but I would prefer to remove information about class from it.这几乎很好,但我更愿意从中删除有关 class 的信息。 Do you have any proposition how to do that?你有什么建议吗?

you can create your own custom ConstraintValidator and annotate your DTO object with corresponding annotation您可以创建自己的自定义 ConstraintValidator 并使用相应的注释注释您的 DTO object

you can find the example here - http://dolszewski.com/spring/custom-validation-annotation-in-spring/您可以在此处找到示例 - http://dolszewski.com/spring/custom-validation-annotation-in-spring/

PS the example is using annotation for one field, but you can use it on the whole class PS该示例对一个字段使用注释,但您可以在整个 class 上使用它

The cleanest way to handle different types of errors in a spring boot REST API is by using spring AOP.在 spring 引导 REST API 中处理不同类型错误的最简单方法是使用 Z2A2D4F065E6BED93B01B3D4F277P。 First, let's create a custom Exception class首先,让我们创建一个自定义异常 class

public class InvalidFormatException extends RuntimeException {

    private final String message;
    private final List<String> data;

    // getters , setters and constructors
}

Then create an error response model class.然后创建一个错误响应 model class。 This model class will provide a JSON structure of what should sent back to the user in case of an exception这个 model class 将提供一个 JSON 结构,说明在发生异常时应该发回给用户的内容

public class ErrorResponseModel {
    
    String code;
    String type;
    String message;
    List<String> data;

    // getters, setters, and constructor
}

Then create a custom exception handler for your controller using spring AOP然后使用 spring AOP 为您的 controller 创建一个自定义异常处理程序

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(InvalidFormatException.class)
    public ResponseEntity<ErrorResponseModel> badRequestException(InvalidFormatException ex, WebRequest request) {
        return new ResponseEntity<>(new ErrorResponseModel(ex.getMessage(), ex.getData()),
                HttpStatus.BAD_REQUEST);
    }
}

You can add and handle more error types like this in this class.您可以在此 class 中添加和处理更多类似的错误类型。 Now whenever you throw an Exception, it will be intercepted here and a custom error response will be sent back to the user.现在,每当您抛出异常时,它都会在此处被拦截,并将自定义错误响应发送回用户。

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

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