How to get the Only the message form ConstraintViolationException

153 Views Asked by At

i have this code to deal with ConstraintViolationException to return only the message that in the constrains

 @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(BAD_REQUEST)
    @ResponseBody
    public final ResponseEntity<ErrorMessage> handleConstraintViolationException( ConstraintViolationException ex ) {

        ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), "400");

        return new ResponseEntity<>(errorMessage, BAD_REQUEST);
    }

here the entity class

package com.courses.restapi.entities.courses;

import com.courses.restapi.entities.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;

import jakarta.persistence.Table;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.math.BigDecimal;


@Entity
@Table(name = "courses")

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Course extends BaseEntity {


    @NotNull
    @NotBlank(message = "title may not be blank")
    @Column( name = "title", length = 100)
    @Size(max = 100 ,message = " title may not be longer than 100 ")
    private String title;


    @NotNull
    @NotBlank(message = "description may not be blank")
    @Column( name = "description", length = 1000)
    @Size(max = 1000 ,message = " description may not be longer than 100 ")
    private String description;


    @NotNull(message = " price may not be null")
    @DecimalMin("1.00")
    private BigDecimal price;

}

this is the response when we try to add Course with blank description

{
    "message": "Validation failed for classes [com.courses.restapi.entities.courses.Course] during persist time for groups [jakarta.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='description may not be blank', propertyPath=description, rootBeanClass=class com.courses.restapi.entities.courses.Course, messageTemplate='description may not be blank'}\n]",
    "code": "400"
}

What should I do to return only the message whish is "description may not be blank" in the response

I tried Exception inested of ConstraintViolationException but still same problem

0

There are 0 best solutions below