In this tutorial of Spring boot Exception Handling we will see how to create own custom exception handler and a mechanism to handle various kinds of exceptions in REST endpoints.
And in the below exception handler you can add your own thought of methods to handle exceptions.
Let’s Begin
1. RestController – Create
@GetMapping("/dependant/dept-id/{id}")
@ResponseBody
public Dependant getDependantbyId(@PathVariable int id){
if(id>10){
throw new MyCustomException("the id is not in range");
}
Dependant dept = new Dependant();
dept = dependantRepository.findBydeptid(id);
return dept;
}
2. Custom Exception Class – Create
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class MyCustomException extends RuntimeException {
public MyCustomException(String message){
super(message);
}
}
3. Controller Advice – Custom Exception Handler
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
System.out.println("Inside handleAllExceptions() method of CustomExceptionHandler");
return new ResponseEntity("This is a General Exception....", HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(MyCustomException.class)
public final ResponseEntity<Object> handleUserNotFoundException(MyCustomException ex, WebRequest request) {
System.out.println("Inside handleUserNotFoundException() method of CustomExceptionHandler method");
return new ResponseEntity("This is MyCustomException.....", HttpStatus.NOT_FOUND);
}
}
OUTPUT
GET API : http://localhost:8080/api/dependant/dept-id/11
Considering id=11 is not present in the database
We handle this exception using Handler – below is the output of the above code
Status : 404 Not Found
This is MyCustomException…..
Summary
In this tutorial, we learnt how to create own custom exception handler and a mechanism to handle various kinds of exceptions in REST endpoints.
We Used spring annotations to achieve that using @ExceptionHandler, @ControllerAdvice.
I hope you liked it !