Reputation: 23
So I have various API endpoints defined in my Spring Boot
services that throws various custom exceptions. But I am not able to make a distinction between Checked and Unchecked exceptions.
So should my custom exception be Checked or Unchecked exception?
Examples:
These exceptions are parsed by Spring ControllerAdvice
, converted to ResponseEntity and sent to client.
How would you define above custom created exceptions as Checked or Unchecked? Also let me know if there is any thumb rule to decide if your exception should be Checked or Unchecked?
Upvotes: 0
Views: 2113
Reputation: 1726
try defining all of them as unchecked
and define a method for each type of exception where you need specific handling with @ExceptionHandler
in ControllerAdvice
@ExceptionHandler(value = { EmailAlreadyExistsException.class, UserAlreadyExistsException.class })
protected ResponseEntity<Object> handleAlreadyExistsException(RuntimeException ex, WebRequest request) {
String yourErrMsg = "Some error desc.."
List<String> errorMessages = List.of(yourErrMsg);
HttpStatus httpStatusForTheError = HttpStatus.BAD_REQUEST;
return new ResponseEntity<List<String>>
(errorMessages, httpStatusForTheError);
}
and one final method as a catch all
@ExceptionHandler(value = RuntimeException.class)
protected ResponseEntity<Object> handle EmailAlreadyExistsException(RuntimeException ex, WebRequest request) {
String yourErrMsg = "We are sorry, something went wrong."//don't disclose the stacktrace
List<String> errorMessages = List.of(yourErrMsg);
return new ResponseEntity<List<String>>
(errorMessages, HttpStatus.INTERNAL_SERVER_ERROR);
}
example from: https://www.baeldung.com/exception-handling-for-rest-with-spring
Upvotes: 1
Reputation: 2730
Also let me know if there is any thumb rule to decide if your exception should be Checked or Unchecked?
Checked Exception
the compiler check and force you to handle the exception
Unchecked Exception
the compiler does not warn you and you handle the exception by yourself
The rule you can adopt is the following
Checked Exception
. It will force you to handle your exception in top layers (service > controller)Read this for more details.
Upvotes: 0
Reputation: 21883
You are good even if you have all your exceptions as RuntimeException
since you delegate error response generation to ControllerAdvice
.
Regardless of whether it is a RESTful Spring Boot Service or just another Java Application the premise to throw Checked or Unchecked Exceptions from a method largely remains on whether the caller MUST (Checked) or SHALL (Runtime) handle exception.
For example when calling
FileInputStream fis = new FileInputStream("somefile.txt");
The constructor FileInputStream(String fileName)
forces to handle the File not found exceptional scenario. Thus it throws a FileNotFoundException
which is a checked exception and MUST be handled by the caller at the calling location itself.
Upvotes: 1