In Spring Rest, there is a provision of handling exception by having a separate class dedicated to handling exceptions.
We will se that later below. For now, consider the below get request and get method which handles any get request directed towards the employees controller.

com.techfinanceworld.restapp.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("employees")
public Class EmpController{
@GetMapping(path="/{empId}",produces = {MediaType.APPLICATION_JSON_VALUE})
public String getEmployee(@PathVariable String empId)
{
String empName = null; \\Line 4
int length = empName.length(); \\Line 5
System.out.println("EmpID fetched VIA get request is "+empId); \\Line 5
}
}
If you check the above GET method, it accepts the emp id as a path variable. After checking the request sent through PostMan UI above, it was sent as 100.
But main problem is in line 4 and line 5. It would result in Null Pointer Exception. So how to handle this exception which would happen in the above method in the rest controller?
com.techfinanceworld.restapp.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public Class AppExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {Exception.class})
public ResponseEntity<Object> handleAnyException(Exception ex, WebRequest request){
return new ResponseEntity<>(
ex,new HttpHeaders(), HttpsStatus.INTERNAL_SERVER_ERROR);
}
}
The above class is an user exception class specially designed to handle exceptions occuring inside a rest controller.
The @ControllerAdvice annotation is used with the class so that it is mapped to the Controller class. The method handling the exception is annotated with @ExceptionHandler.
It returns an response entity object which contains the error response code(HttpsStatus.INTERNAL_SERVER_ERROR) to be sent to the client with the details in a JSON format in case an exception occurs.