简体   繁体   中英

How do I configure a custom error message when using @JsonFormat?

I got a problem here where I can't accept wrong date formats.

For example:

If the api request receive a date "2019-14-10" I can't accept it. Right now when I receive that, JsonFormat gives me 2020-02-10.

To solve this, I added the lenient=OptBoolean.FALSE as shown here:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "America/Vancouver", lenient = OptBoolean.FALSE)
private Date effectiveDate;

The problem now is that when I call the api passing a wrong date (2019-14-10) I just get back a 400 Bad request response.

Is it possible to create a custom response to this validation?

For instance, can I return something like this:

{
  "code": {
    "value": 4,
    "name": "InvalidRequest"
  },
  "message": "{effectiveDate=Date is invalid. Please choose a valid date}"
}

Or at least the error message.

This wouldn't be something handled by Jackson directly. This is something that a higher order validation API would handle, like bean validators .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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