Employee Management System Handling Exception

Learn via video courses
Topics Covered

Overview

The Employee Management System that we developed, works functionally; however, it needs to handle the exceptions properly.

Prerequisite

  • User should refer to this code that we’ll work upon.

Handle Exception

The current test report for the employee management system has some failures. Handle exception

  1. test_delete_employee is failing because the expected status code is 204, but our API returned 200.
  2. test_create_employee is failing because it expects status code 201, but our API returned 200.
  3. test_GetEmployee_employeeNotFound is failing because our service throws the exception EmployeeNotFoundException, which is not handled in the web layer.

Let's go ahead and fix each of them.

Fix Delete Employee API

Spring boot always defaults to the status code 200 OK if API does not return the status code explicitly. To return specific HTTP code, spring boot provides annotation @ResponseStatus, which should be applied to the handler method. Our code change with the fix will be.

Fix Create New Employee

The same change applies to creating an employee method.

Applying the above changes leaves us with only one failure. Fix create new employee

Fix Employee Not Found Exception

Here, we need to use controller advice to handle exceptions and return meaningful content to the user. We need to return a custom response to the user. Let's do that.

1. Create a custom response POJO.

2. Write controller advice

The above code intercepts the exception and returns the response to the user with the status code 404, which goes well with REST.

Our latest test report. Fix employee not found exception Test Report

The actual response to the API caller Fix employee not found exception Actual Response

Complete source code is available at GitHub location under tag version_7.0.0.

Conclusion

In this article, we have

  • Improved employee management system to be more RESTful.
  • Handled exceptions and returned a meaningful response to the user.