Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to throw exception from DAO layer to controller?

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?

like image 677
Ravindra Thorat Avatar asked Mar 18 '15 05:03

Ravindra Thorat


People also ask

How do you handle exceptions in DAO layer?

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.

Is it good practice to throw exception?

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.

Should I throw exception in controller?

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.

Should you handle exceptions in service or controller?

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).


1 Answers

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.

like image 187
Rohit Jain Avatar answered Nov 04 '22 12:11

Rohit Jain