-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathValidationExceptionHandler.java
More file actions
34 lines (27 loc) · 1.12 KB
/
ValidationExceptionHandler.java
File metadata and controls
34 lines (27 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.example.labweek5.controller;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, List<String>>> handleValidationErrors(
MethodArgumentNotValidException ex) {
Map<String, List<String>> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(error -> {
String field = error.getField();
String message = error.getDefaultMessage();
errors.computeIfAbsent(field, k -> new ArrayList<>())
.add(message);
});
return ResponseEntity
.badRequest()
.body(errors);
}
}