[SOLVED] Micronaut POJO deserialisation error message when the format is invalid or type throws error

Issue

This Content is from Stack Overflow. Question asked by two-touch

When providing the incorrect format of a field for a request to my application if the type throws an error then the error message returned by micronaut is vague.

E.G two scenarios

public class fakeClass {
    @NotNull
    private String fakeName;
}

if my request is {"fakeName": ""}

then the response, correctly, would be something like

{
"violations": [
    {
        "field": "create.fakeClass.fakeName",
        "message": "must not be blank"
    }
],
"type": "https://zalando.github.io/problem/constraint-violation",
"title": "Constraint Violation",
"status": 400 }

But lets say my class looks like this:

   public class fakeClass {
    @Format("yyyy-MM-dd")
    private LocalDate exampeDate;
}

With an invalid date or incorrect format of {"exampleDate": 202222--01-01} or {"exampleDate": 2022/01/01}

Then the error message is

{
"type": "about:blank",
"parameters": {
    "path": "/project"
},
"status": 400,
"detail": "Required argument [fakeClass fakeClass] not specified"

}

Is there a simple way to provide more information to the error message to make it clear why the request failed for an invalid format or type like @NotNull or @NotBlank?



Solution

The problem here is not Micronaut but your payloads. The examples you mentioned are invalid JSON documents.

For example this on here is invalid, since the value is not a number nor a string.

{
  "exampleDate": 202222--01-01
}

this would be the a valid variant

{
  "exampleDate": "202222--01-01"
}

Make sure you send the date as a String. In your case this is expected to be valid.

{
  "exampleDate": "2022-11-01"
}

In general it is recommended to send date using the ISO-8601 format, which you did (yyyy-MM-dd). Furthermore I recommend to apply a global configuration rather than using on each POJO a @Format("yyyy-MM-dd") annotation.

jackson:
  dateFormat: yyyyMMdd
  timeZone: UTC
  serializationInclusion: NON_NULL
  serialization:
    writeDatesAsTimestamps: false


This Question was asked in StackOverflow by two-touch and Answered by saw303 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?