I am writing one REST api. There might be two exceptions in my DAO layer namely Exception_X
and Exception_Y
. If I encountered a exception Exception_X
in DAO layer, my controller should return status code 200
, if Exception_Y
then 401
and if all goes well controller should return 201
.
Now what was I thinking that I will throw encountered exception as it is from DAO layer to controller via service layer and in catch
block of controller I will return response.
Is it acceptable or there is some other standard way?
its a good idea to create your own independant exceptions for each layer. For example, if you are using a particular DAO implementation, you should wrap the implementation specific exception to your own generic exception and throw it forward to Service Layer.
It is good practice to throw exceptions if you have appropriate exception handling. Don't blindly throw exceptions until the application crashes. In your option 1 example, an ArgumentException is more appropriate. Your option 2 is more appropriate for data validations.
Exceptions are not a good way to do it, although possible. Validations should return boolean true or false to the controller, and then the controller returns a response to the user with an explanatory message. Don't return code 500 for validations; that code is meant for server errors, not user errors.
You should make your services transactional and handle the exceptions in the Controller layer: you may choose Controller Based Exception Handling (Using @ExceptionHandler ) or Global Exception Handling (Using @ControllerAdvice Classes).
Yes that is quite an acceptable way. However, rather than using try-catch
, I would suggest to implement Exception Handlers for your REST Controllers. That way, you won't have to clutter your REST methods.
Also, it would be better to create a model object in REST layer for Error messages - ErrorResponse
, with appropriate information:
class ErrorResponse {
int statusCode;
String errorMessage;
}
And return it's object from the exception handlers. BTW, you can also map your exception class directly to a response using @ResponseStatus
annotation:
@ResponseStatus(value=401, reason="message")
class Exception_Y extends RuntimeException {
}
Then you don't have to write exception handler for that exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With