Skip to content

Commit

Permalink
api validation exception handled
Browse files Browse the repository at this point in the history
  • Loading branch information
anishmu20 committed Nov 6, 2024
1 parent 5cdb29e commit 2cee8a5
Showing 1 changed file with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.Date;
import java.util.*;

/**
* Global exception handler for the LibraryMan API. This class provides
Expand Down Expand Up @@ -69,4 +73,18 @@ public ResponseEntity<?> invalidPasswordException(InvalidPasswordException ex, W
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String,Object>> MethodArgumentNotValidException(MethodArgumentNotValidException ex){
List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
HashMap<String,Object> map = new HashMap<>();
allErrors.forEach(objectError -> {
String message=objectError.getDefaultMessage();
String field=((FieldError) objectError).getField();
map.put(field,message);
});

return new ResponseEntity<>(map,HttpStatus.BAD_REQUEST);
}

}

0 comments on commit 2cee8a5

Please sign in to comment.