0

With java validation constraints, i.e.

@NotNull, @Size, etc

You can add a message field that your api can return to the client. Is there anyway to add additional fields such as a custom code?

The problem I have is that every possible error needs it's own message and code return to the client. (By code I mean a custom one in the response body, not a http status code).

I.e.

{
  message: foo can not be null,
  code: 10001
}

The only thing I can think of is to use custom validator classes on every single field which would be quite a lot of work, or have a giant if/else block that sets the code based on the message.

Can anyone think of a nicer solution?

Thanks in advance for any help :)

2
  • How about formatting your message as "10001|foo can not be null", and then split any message you get and parse the code from the first part and the message from the second part? Commented Aug 3, 2016 at 13:04
  • That's the solution I'm currently going with. It's still not very nice. Another problem is that my error messages are in a ValidationMessages.properties file and injected as message="{Missing.foo}". To include the code in the message, the codes will also have to be in the ValidationMessages.properties file as well. Again, it's not a very nice solution. Commented Aug 3, 2016 at 13:08

1 Answer 1

1

You can use the payload() parameter defined by all constraint types.

You'd have to declare a class type for each one of your error codes:

public interface Error_01 {}

And then:

public class SomeValidatedClass {
    @NotNull(payload=Error_01.class)
    private String someField;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that looks like that might be a nicer solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.