Open DevShivmohan opened 1 year ago
Declare in Global exception handler
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler{
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException methodArgumentNotValidException){
log.error("Args");
Map<String,String> map=new HashMap<>();
methodArgumentNotValidException.getBindingResult()
.getAllErrors().forEach(error->map.put(((FieldError)error).getField(),error.getDefaultMessage()));
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(map);
}
}
Validating in DTO or Entity
@Data
@Builder
public class AuthRequest {
@NotBlank(message = "Username cannot be blank")
@Size(min = 3,message = "Must be 3 chars")
@Pattern(regexp = "[0-9a-zA-Z]+",message = "Username must contain alpha numeric value")
private String username;
private String password;
}
Enable validation during accept request body using @Valid annotation like below
@PostMapping("/login")
public ResponseEntity<?> login(@Valid @RequestBody AuthRequest authRequest){
log.info("Request hits-"+authRequest);
return authenticationService.login(authRequest);
}
If you need extra information than please refer this Link
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Collections;
import java.util.Set;
@Entity
@Table(name = "business")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Business {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "business_id")
private Integer id;
private String name;
@ElementCollection
@CollectionTable(name = "user_ids",joinColumns = @JoinColumn(name = "business_id"))
private Set<Integer> userIds= Collections.emptySet();
}
Reference to learn mappings in JPA - Relationship mapping JPA
Inside entity class validate field with respected validations like that
implement below code inside exception handler class, these are return to the client as a response