Spring Boot how to return my own validation constraint error messages

user745235 picture user745235 · Jul 13, 2018 · Viewed 16.6k times · Source

I need to have my own error response body when something goes wrong with my request and I am trying to use the @NotEmpty constraint message attribute to return the error message,

This is my class that returns the error message using the body that I need:

package c.m.nanicolina.exceptions;


import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    public ResponseEntity<ApiError> handleConflict(MissingServletRequestParameterException ex, WebRequest request) {
        ApiError apiError = new ApiError(ex.getMessage(), ex.getMessage(), 1000);
        return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
    }
}

With this CustomResponseEntityExceptionHandler I can return my own response body in case of validation errors.

What I am trying now is to get the message from the validation constraints.

This is my controller with the NotEmpty constraint:

package c.m.nanicolina.controllers;

import c.m.nanicolina.models.Product;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;

@RestController
public class MinimumStockController {

    @RequestMapping(value = "/minimumstock")
    public Product product(
            @RequestParam(value = "product.sku") @NotEmpty(message = "Product.sku cannot be empty") String sku,
            @RequestParam(value = "stock.branch.id") String branchID) {
        return null;
    }
}

In my exception, I can't find a way to get that message Product.sku cannot be empty and show it in my error response.

I have also checked the class MissingServletRequestParameterException and there is the method getMessage which is returning the default message.

Answer

Amith Kumar picture Amith Kumar · Jul 14, 2018

Yes it is doable & spring very well supports it. You are just missing some configuration to enable it in spring.

  • Use Spring@Validated annotation to enable spring to validate controller
  • Handle ConstraintViolationException in your ControllerAdvice to catch all failed validation messages.
  • Mark required=false in @RequestParam, so it will not throw MissingServletRequestParameterException and rather move to next step of constraint validation.
@ControllerAdvice
public class CustomResponseEntityExceptionHandler {

    @ExceptionHandler
  public ResponseEntity<ApiError> handle(ConstraintViolationException exception) {
        //you will get all javax failed validation, can be more than one
        //so you can return the set of error messages or just the first message
        String errorMessage = new ArrayList<>(exception.getConstraintViolations()).get(0).getMessage();
       ApiError apiError = new ApiError(errorMessage, errorMessage, 1000);    
       return new ResponseEntity<ApiError>(apiError, null, HttpStatus.BAD_REQUEST);
  }
}



@RestController
@Validated
public class MinimumStockController {

    @RequestMapping(value = "/minimumstock")
    public Product product(
            @RequestParam(value = "product.sku", required=false) @NotEmpty(message = "Product.sku cannot be empty") String sku,
            @RequestParam(value = "stock.branch.id", required=false) String branchID) {
        return null;
    }
}

NOTE: MissingServletRequestParameterException won't have access to javax validation messages, as it is thrown before constraint validation occurs in the request lifecycle.