/
podkmax
/
spring-test
Обзор
Документация
Войти
/
podkmax
/
spring-test
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/main/java/com/example/springtests/common/GlobalExceptionHandler.java
37 строк
2 KB
Maksim.Podkorytov
sb test example
04 май 2026, 15:40
04 май 2026, 15:40
8288ba1
Код
Авторство
О чём код?
package com.example.springtests.common; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.util.stream.Collectors; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException exception) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ErrorResponse(exception.getMessage())); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException exception) { String message = exception.getBindingResult() .getFieldErrors() .stream() .map(error -> error.getField() + " " + error.getDefaultMessage()) .collect(Collectors.joining("; ")); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResponse(message)); } @ExceptionHandler(DataIntegrityViolationException.class) public ResponseEntity<ErrorResponse> handleDataIntegrityViolation(DataIntegrityViolationException exception) { return ResponseEntity.status(HttpStatus.CONFLICT).body(new ErrorResponse("User with this email already exists")); } public record ErrorResponse(String message) { } }