Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @PostMapping
- public ResponseEntity<HttpStatus> saveStudent(@Valid @RequestBody StudentDto dto, BindingResult br){
- if (br.hasErrors()) {
- throw new InvalidRequestException("Wrong resource", br);
- }
- divisionService.saveStudent(dto);
- return new ResponseEntity<>(HttpStatus.CREATED);
- }
- if (br.hasErrors()) {
- throw new InvalidRequestException("Wrong resource", br);
- }
- @ControllerAdvice
- public class ValidationErrorHandlingAdvice {
- /**
- * Handler for {@link MethodArgumentNotValidException}s. These are triggered by
- * Spring {@link Validator} implementations being invoked by the Spring MVC
- * controllers and returning validation errors.
- *
- *
- * @param ex The {@link MethodArgumentNotValidException} to be handled.
- *
- * @return {@link Map} keyed by field to which the error is bound and with the
- * value of the field as a value.
- */
- @ResponseStatus(code = HttpStatus.BAD_REQUEST)
- @ExceptionHandler(MethodArgumentNotValidException.class)
- public @ResponseBody ValidationErrors handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
- Map<String, List<String>> errorMap = new TreeMap<>();
- BindingResult result = ex.getBindingResult();
- for (FieldError error : result.getFieldErrors()) {
- if (!errorMap.containsKey(error.getField())) {
- errorMap.put(error.getField(), new ArrayList<String>());
- }
- errorMap.get(error.getField()).add(error.getDefaultMessage());
- }
- return new ValidationErrors(errorMap);
- }
- private static class ValidationErrors {
- private Map<String, List<String>> errors;
- public ValidationErrors(Map<String, List<String>> errors) {
- this.errors = errors;
- }
- @SuppressWarnings("unused")
- public Map<String, List<String>> getErrors() {
- return errors;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement