
In this article, we will see how we can create a custom user exception class and configure the same to use in the Spring Rest Controller.
First step would be to create an User Custom Exception Class.
public class UserException extends RunTimeException{
public UserException(String s){
super(s);
}
}
Now create a handler for ths user exception in an controller exception handler class.
@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);
}
@ExceptionHandler(value = {UserException.class})
public ResponseEntity<Object> handleUserException(UserException ex, WebRequest request){
return new ResponseEntity<>(
ex,new HttpHeaders(), HttpsStatus.INTERNAL_SERVER_ERROR);
}
}
A new handler method is created for the same named as handleUserException as sen above.
Now let’s thow the exception in rest controller method.
@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
if (empName == null); \\Line 5
{
throw new UserException("User Exception is thrown. Name is null");\\Line 6
}
System.out.println("EmpID fetched VIA get request is "+empId);
}
}
At line 6, we can see the custom user exception being thrown due to null emp name.