/
spirzen
/
it-code-examples
Обзор
Документация
Войти
/
spirzen
/
it-code-examples
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
examples/java/java-503-254-005/main.java
38 строк
2 KB
Spirzen
Code migration pack
09 июн 2026, 01:41
09 июн 2026, 01:41
cebc284
Код
Авторство
О чём код?
package com.example.crm.config; import com.example.crm.service.CustomerNotFoundException; 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.RestControllerAdvice; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; @RestControllerAdvice public class RestExceptionHandler { @ExceptionHandler(CustomerNotFoundException.class) public ResponseEntity<Map<String, String>> handleNotFound(CustomerNotFoundException ex) { Map<String, String> body = Map.of("error", ex.getMessage()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException ex) { Map<String, String> errors = ex.getBindingResult().getFieldErrors().stream() .collect(Collectors.toMap( error -> error.getField(), error -> error.getDefaultMessage() != null ? error.getDefaultMessage() : "Invalid value", (first, second) -> first, LinkedHashMap::new )); Map<String, Object> body = new LinkedHashMap<>(); body.put("error", "Validation failed"); body.put("fields", errors); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body); } }