mdhtr / java-webapplication

Building a java web application step by step
0 stars 0 forks source link

Add example of json input validation with meaningful error response #11

Closed mdhtr closed 4 years ago

mdhtr commented 4 years ago

Required field validation + list all missing fields is response

mdhtr commented 4 years ago

This issue consists of two parts, the first part is to validate the input and throw an exception with validation results, the second is to catch that exception, and return it in a good format.

For the first part, there is several ways to do validation, I will elaborate in separate comments below.

For the second part, the Problem Details spec can come in handy: https://tools.ietf.org/html/rfc7807

Some references:

mdhtr commented 4 years ago

Option A: custom setter

Tl;dr:

Pros:

Cons:

mdhtr commented 4 years ago

Option B: custom deserializer

Tl;dr:

Pros:

Cons:

  1. provide a custom deserializer to the bean
    @JsonDeserialize(using = TestValidationDtoDeserializer.class)
    public class TestValidationDto {
    ...
  2. implement the deserializer

    public class TestValidationDtoDeserializer extends JsonDeserializer {
    @Override
    public TestValidationDto deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    
                ... // throw custom exception on validation error
    
        return new TestValidationDto( ... );
    }
mdhtr commented 4 years ago

Option C: JsonCreator

Tl;dr:

Pros:

Cons:

mdhtr commented 4 years ago

Option D: custom converter + javax.validation

Tl;dr:

Pros:

Cons:

mdhtr commented 4 years ago

I chose option D: custom converter + javax.validation. The javax validation annotations make specifying validations easy, and the custom converter is highly reusable and easy to use.

mdhtr commented 4 years ago

A possible future improvement could be to return the validation errors is a machine parsable format, in an additional field.