We have a micro service based architecture which consists of main apps server module and libs modules. In main app server, we are just accepting request and providing response via a request and response object on the REST API methods which call service layers available in libs module.
parent--
------apps
---server
---Controller Class
------libs
---core
---Service Layer
---Dao Layer
To propagate the error messages so that they can be send over to clients using Response Object(available only in Controller classes), we are throwing custom exceptions in service layer, so that we can send error message to Controller classes. The problem with this approach is that we are throwing exception in all cases as an example we throw exception even when an input is not correct or when user is not having permission, where in we can just return a response to user with the error message.
My question is that - Is it a correct approach to throw Custom exception just for the sake of propagating error messages from Service layer to Controller? If NO, then how we can propagate error message to controller layer?
Service Layer ---
public String serviceLayerMethod(String param) throws AssetException {
try {
if(param==null){
throw new CustomException;
} else{
return param;
}
} catch (CustomException e) {
LOGGER.error(CustomExceptionEnum.PARAMNULL_EXCEPTION.getMessage(),e);
throw new CustomException(CustomExceptionEnum.PARAMNULL_EXCEPTION.getMessage(), e);
}
}
Controller Layer ---
public Response restAPI(Request request) {
try {
response.setMessage(service.serviceLayerMethod());
response.setSuccess(true);
} catch (CustomException e) {
response.setMessage(e.getMessage());
response.setSuccess(false);
}
return response
}