Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Exceptionhandler & ExceptionHandlerTest classes #228

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

Krushit-Babariya
Copy link

Exception Handling

1. Exception Handling (ExceptionHandler class):
The ExceptionHandler class is annotated with @ControllerAdvice, which allows it to handle exceptions globally for the entire application. It has handlers for the following exceptions:
NoSuchElementException: Returns a 404 Not Found response when an element, such as an employee, is not found.
IllegalArgumentException: Returns a 400 Bad Request when an invalid UUID or other bad input is encountered.
MethodArgumentNotValidException: Handles validation errors, capturing invalid input fields and their associated messages, returning a 400 Bad Request.
Generic Exception: Catches all other unhandled exceptions, returning a 500 Internal Server Error.

2. Unit Testing (ExceptionHandlerTest class):
The ExceptionHandlerTest class contains unit tests to ensure that each exception handler in the ExceptionHandler class behaves as expected. It tests:
Correct handling of NoSuchElementException, ensuring it returns a 404 status.
Handling of IllegalArgumentException, verifying a 400 status.
Proper validation error handling (MethodArgumentNotValidException) by mocking field validation and checking that it returns the appropriate errors.
A generic Exception handler that ensures unexpected errors result in a 500 Internal Server Error.

Copy link
Author

@Krushit-Babariya Krushit-Babariya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Changes..!

@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity<Object> handleNoSuchElementException(NoSuchElementException ex) {
String message = "Employee not found: " + ex.getMessage();
return new ResponseEntity<>(message, HttpStatus.NOT_FOUND);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See

I've already have a test that works without this ExceptionHandler.
Prove to me the necessity and usefulness of your code through an integration test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants