Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. @PostMapping
  2. public ResponseEntity<HttpStatus> saveStudent(@Valid @RequestBody StudentDto dto, BindingResult br){
  3. if (br.hasErrors()) {
  4. throw new InvalidRequestException("Wrong resource", br);
  5. }
  6.  
  7. divisionService.saveStudent(dto);
  8. return new ResponseEntity<>(HttpStatus.CREATED);
  9. }
  10.  
  11. if (br.hasErrors()) {
  12. throw new InvalidRequestException("Wrong resource", br);
  13. }
  14.  
  15. @ControllerAdvice
  16. public class ValidationErrorHandlingAdvice {
  17.  
  18. /**
  19. * Handler for {@link MethodArgumentNotValidException}s. These are triggered by
  20. * Spring {@link Validator} implementations being invoked by the Spring MVC
  21. * controllers and returning validation errors.
  22. *
  23. *
  24. * @param ex The {@link MethodArgumentNotValidException} to be handled.
  25. *
  26. * @return {@link Map} keyed by field to which the error is bound and with the
  27. * value of the field as a value.
  28. */
  29. @ResponseStatus(code = HttpStatus.BAD_REQUEST)
  30. @ExceptionHandler(MethodArgumentNotValidException.class)
  31. public @ResponseBody ValidationErrors handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
  32. Map<String, List<String>> errorMap = new TreeMap<>();
  33.  
  34. BindingResult result = ex.getBindingResult();
  35. for (FieldError error : result.getFieldErrors()) {
  36.  
  37. if (!errorMap.containsKey(error.getField())) {
  38. errorMap.put(error.getField(), new ArrayList<String>());
  39. }
  40.  
  41. errorMap.get(error.getField()).add(error.getDefaultMessage());
  42. }
  43.  
  44. return new ValidationErrors(errorMap);
  45. }
  46.  
  47.  
  48. private static class ValidationErrors {
  49. private Map<String, List<String>> errors;
  50.  
  51. public ValidationErrors(Map<String, List<String>> errors) {
  52. this.errors = errors;
  53. }
  54.  
  55. @SuppressWarnings("unused")
  56. public Map<String, List<String>> getErrors() {
  57. return errors;
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement