handle validation errors

This commit is contained in:
Stepan Usatiuk
2023-12-30 14:42:07 +01:00
parent 3165137475
commit ece5519b3b
6 changed files with 18 additions and 4 deletions

View File

@@ -9,6 +9,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
@@ -27,6 +28,18 @@ public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(TransactionSystemException.class)
protected ResponseEntity<Object> handleTransactionSystemException(TransactionSystemException ex, WebRequest request) {
if (ex.getRootCause() instanceof ConstraintViolationException) {
return handleConstraintViolation((ConstraintViolationException) ex.getRootCause(), request);
} else {
return handleExceptionInternal(ex,
new ErrorTo(List.of("Error"), HttpStatus.INTERNAL_SERVER_ERROR.value()),
new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}
@ExceptionHandler(AuthenticationException.class)
protected ResponseEntity<Object> handleAuthenticationException(AuthenticationException ex, WebRequest request) {
return handleExceptionInternal(ex,

View File

@@ -22,7 +22,7 @@ public class Chat {
@GeneratedValue
private Long id;
@NotBlank
@NotBlank(message = "Name can't be empty")
private String name;
@OneToMany(mappedBy = "chat", orphanRemoval = true)

View File

@@ -32,6 +32,6 @@ public class Message {
private Instant createdAt;
@Lob
@NotBlank
@NotBlank(message = "Message can't be empty")
private String contents;
}

View File

@@ -31,6 +31,7 @@ public class Person {
@Size(max = 100, message = "Name can't be longer than 100")
@NotBlank(message = "Name can't be empty")
private String fullName;
@NotBlank(message = "Password can't be empty")
private String password;

View File

@@ -25,8 +25,8 @@ public class Post {
@ManyToOne
private Person author;
@NotBlank
@Lob
@NotBlank(message = "Post can't be empty")
private String text;
@CreationTimestamp

View File

@@ -37,7 +37,7 @@ public class WebSecurityConfig {
}
@Component
class ErrorAuthenticationEntryPoint implements AuthenticationEntryPoint {
static class ErrorAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final HandlerExceptionResolver resolver;