Reputation: 51
I have this code in which I make a request to the service, if there is no department with that id, my method in the service class will throw a custom exception which I catch in the method from this controller, when I catch the exception, I return a response entity with the error message and HTTP status to the endpoint. I was informed that I don't need to catch the exception here, I just need to catch it in general exception handler. Right now I don't understand what that means.
@GetMapping("/departments/{departmentId}")
public ResponseEntity<Object> getDepartmentById(@PathVariable("departmentId") Long departmentId) {
DepartmentDTO departmentDTO = null;
logger.debug("Entering get item by id endpoint");
try {
departmentDTO = departmentService.getDepartmentById(departmentId);
logger.info("Returned department with id: " + departmentId);
} catch (ApiException e) {
logger.error("Unable to return department with ID: " + departmentId + " ,message: " + e.getMessage(), e);
return GeneralExceptionHandler.handleExceptions(e);
}
return ResponseEntity.ok().body(departmentDTO);
}
this is my exception handling class
@ControllerAdvice
public class GeneralExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GeneralExceptionHandler.class);
@ExceptionHandler(value = {ApiException.class})
public static ResponseEntity<Object> handleExceptions(ApiException e) {
logger.info("Exception handled:"+e.getMessage()+" with http status: "+e.getHttpStatus());
return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
}
}
Upvotes: 0
Views: 1169
Reputation: 333
To use a general exception handler, you can remove the try-catch block in your controller method and just let the exception be thrown. The exception will then be caught by the @ExceptionHandler method in your GeneralExceptionHandler class.
Your controller can be simplified to the following:
@GetMapping("/departments/{departmentId}")
public ResponseEntity<Object> getDepartmentById(@PathVariable("departmentId") Long departmentId) {
logger.debug("Entering get item by id endpoint");
DepartmentDTO departmentDTO = departmentService.getDepartmentById(departmentId);
logger.info("Returned department with id: " + departmentId);
return ResponseEntity.ok().body(departmentDTO);
}
If a ApiException is thrown in the departmentService.getDepartmentById method, it will be caught by the @ExceptionHandler method in your GeneralExceptionHandler class, which will log the exception and return a response with the error message and HTTP status code specified in the ApiException.
This way, you can centralize the exception handling logic in your GeneralExceptionHandler class and avoid duplicating the exception handling code in multiple controllers.
Upvotes: 3