43 lines
1.6 KiB
Java
43 lines
1.6 KiB
Java
package ru.soune.no_copy.handler;
|
|||
|
|
|
||
|
|
import lombok.AllArgsConstructor;
|
||
|
|
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||
|
|
import org.springframework.http.HttpStatus;
|
||
|
|
import org.springframework.http.ResponseEntity;
|
||
|
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||
|
|
import org.springframework.web.bind.annotation.ResponseStatus;
|
||
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||
|
|
import ru.soune.no_copy.exception.UserAlreadyExistsException;
|
||
|
|
|
||
|
|
import java.util.Map;
|
||
|
|
|
||
|
|
@RestControllerAdvice
|
||
|
|
@AllArgsConstructor
|
||
|
|
public class GlobalExceptionHandler {
|
||
|
|
|
||
|
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||
|
|
public ResponseEntity<?> handleValidationException(MethodArgumentNotValidException ex) {
|
||
|
|
String message = ex.getBindingResult().getFieldErrors().stream()
|
||
|
|
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||
|
|
.findFirst()
|
||
|
|
.orElse("");
|
||
|
|
|
||
|
|
return ResponseEntity.badRequest()
|
||
|
|
.body(Map.of(
|
||
|
|
"success", false,
|
||
|
|
"message" ,message));
|
||
|
|
}
|
||
|
|
|
||
|
|
@ExceptionHandler(UserAlreadyExistsException.class)
|
||
|
|
@ResponseStatus(HttpStatus.CONFLICT)
|
||
|
|
public ResponseEntity<?> handleUserContainsException(UserAlreadyExistsException ex) {
|
||
|
|
return ResponseEntity.
|
||
|
|
badRequest()
|
||
|
|
.body(Map.of(
|
||
|
|
"success", false,
|
||
|
|
"message" ,ex.getMessage()
|
||
|
|
));
|
||
|
|
}
|
||
|
|
}
|