/
Sturon
/
Diplom
Обзор
Документация
Войти
/
Sturon
/
Diplom
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
backend/src/main/java/ru/diplom/vision/api/ApiExceptionHandler.java
50 строк
2 KB
Sturon
Initial
03 июн 2026, 15:01
03 июн 2026, 15:01
17b44a2
Код
Авторство
О чём код?
package ru.diplom.vision.api; import java.time.LocalDateTime; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.server.ResponseStatusException; @RestControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException exception) { Map<String, String> fieldErrors = new LinkedHashMap<>(); for (FieldError fieldError : exception.getBindingResult().getFieldErrors()) { fieldErrors.put(fieldError.getField(), fieldError.getDefaultMessage()); } return ResponseEntity.badRequest().body(Map.of( "timestamp", LocalDateTime.now(), "status", HttpStatus.BAD_REQUEST.value(), "error", "Validation failed", "fields", fieldErrors )); } @ExceptionHandler(ResponseStatusException.class) public ResponseEntity<Map<String, Object>> handleStatus(ResponseStatusException exception) { HttpStatus status = HttpStatus.valueOf(exception.getStatusCode().value()); return ResponseEntity.status(status).body(Map.of( "timestamp", LocalDateTime.now(), "status", status.value(), "error", exception.getReason() == null ? status.getReasonPhrase() : exception.getReason() )); } @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<Map<String, Object>> handleIllegalArgument(IllegalArgumentException exception) { return ResponseEntity.badRequest().body(Map.of( "timestamp", LocalDateTime.now(), "status", HttpStatus.BAD_REQUEST.value(), "error", exception.getMessage() )); } }