Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3686

Custom error messages in Spring Rest Api validation - ProblemDetails

$
0
0

I am trying to get a ProblemDetail response populated with the message provided on the message attribute of certain controller @Valid annotations.

For example, the message attribute on the @Pattern annotation:

@RestController@RequestMapping("/api")public class Controller {    @GetMapping    private ResponseEntity<String> get(@Valid @RequestParam(name = "param")                                       @Pattern(regexp = "^[a-zA-Z0-9]{6}$",                                               message = "The request parameter must be 6 characters long and consist of alphanumeric characters.")                                       String param)  {        return ResponseEntity.ok().build();    }}

In case of validation error, I would want a response in the form of a problem detail. (cf. spring docs and RFC-7807).

Which in this example would look like:

{"type": "about:blank","title": "Bad Request","status": 400,"detail": "The request parameter must be 6 characters long and consist of alphanumeric characters.","instance": "/api"}

Note: you can enable this kind of output by having a @ControllerAdvice class extend ResponseEntityExceptionHandler

However, the standard output in this case is:

{"type": "about:blank","title": "Bad Request","status": 400,"detail": "Validation failure","instance": "/api"}

'Validation failure' is a hard coded message present in the constructor of the 'HandlerMethodValidationException', which is the exception being thrown in response to the validation error.

One solution is providing the required message with the message code:

problemDetail.org.springframework.web.method.annotation.HandlerMethodValidationException

This works, but limits your messages to be very general. Since another validation error that throws the same exception will have to do with the same message.It also defeats the purpose of those message attributes on the annotations.

From going through the code my initial guess is that this currently is not yet supported by the spring framework. But maybe someone else has a better idea.


Spring boot version: 3.2.2

Spring version: 6.1.3



Viewing all articles
Browse latest Browse all 3686

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>