ControllerAdvice

This commit is contained in:
uPagge 2021-03-22 19:37:14 +03:00
parent f42e720332
commit 6ee6872892
No known key found for this signature in database
GPG Key ID: 964B40928E4C9088
4 changed files with 79 additions and 1 deletions

View File

@ -0,0 +1,48 @@
package org.sadtech.example.springvalidation.controller;
import org.sadtech.example.springvalidation.dto.ValidationErrorResponse;
import org.sadtech.example.springvalidation.dto.Violation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;
@ControllerAdvice
public class ErrorHandlingControllerAdvice {
@ResponseBody
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ValidationErrorResponse onConstraintValidationException(
ConstraintViolationException e
) {
final List<Violation> violations = e.getConstraintViolations().stream()
.map(
violation -> new Violation(
violation.getPropertyPath().toString(),
violation.getMessage()
)
)
.collect(Collectors.toList());
return new ValidationErrorResponse(violations);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorResponse onMethodArgumentNotValidException(
MethodArgumentNotValidException e
) {
final List<Violation> violations = e.getBindingResult().getFieldErrors().stream()
.map(error -> new Violation(error.getField(), error.getDefaultMessage()))
.collect(Collectors.toList());
return new ValidationErrorResponse(violations);
}
}

View File

@ -34,7 +34,10 @@ public class PersonDto {
private int numberBetweenOneAndTen;
@Column(name = "ip_address")
@Pattern(regexp = "^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\\.(?!$)|$)){4}$")
@Pattern(
regexp = "^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\\.(?!$)|$)){4}$",
message = "Не соответствует формату IP адреса"
)
private String ipAddress;
}

View File

@ -0,0 +1,14 @@
package org.sadtech.example.springvalidation.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.List;
@Getter
@RequiredArgsConstructor
public class ValidationErrorResponse {
private final List<Violation> violations;
}

View File

@ -0,0 +1,13 @@
package org.sadtech.example.springvalidation.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public class Violation {
private final String fieldName;
private final String message;
}