ExceptionMapper advantage in jersey - java

I am new to Jersey framework. Just want to know what are the advantages of using exception mapper.
If I want to throw any error to the rest consumer I can do the following in the method,
Response.status(502).entity("Server error during registration").build();
Why it is recommended to use exceptionMapper, please help me understand?

In the particular case of your example, it will have the same effect.
In case the exception is not thrown by you directly but in some code you are calling, for instance from a library, you would have to catch that exception to "map" it manually, in order to have the desired behavior.
Now if you want to treat different kind of exceptions in different ways, you will probably need to have several catch blocks, or use instanceof intensively. And for each new entrypoint of your service, you will have to repeat this exception handling business.
ExceptionMapper is just a clear/scalable way to intercept potential exceptions that may be thrown within the implementation of your service.

Related

Does it make sense to throw an exception which is always chained?

I'm working on a message library and the send method of an object can fail for a number of reasons such as the socket being closed, etc.
I favor checked exceptions over runtime exceptions but I'm wondering if it would then be more appropriate to favor chaining the exceptions early such that the underlying exception is always wrapped in another, more generalized exception.
For example, a message may only throw a checked SendFailedException but the cause() would be more specific such as SocketClosedException. This feels like it would be less cluttered than having all of the checked exceptions being thrown individually.
Inheritance doesn't quite work here as a SocketClosedException can be thrown for other methods as well. And not every closed exception is a result of a failure to send.
Would it be appropriate to wrap further information in cause() or would this end up being more confusing? I don't recall finding exceptions functioning in this way in the wild and this might be unconventional and confusing for others.
Does Java or other libraries ever do this? Is it appropriate for my use case?
Would it be appropriate to wrap further information in cause() or
would this end up being more confusing ?
You can always use cause to wrap the original exception which will provide more details about the root/origin of the exception in the stacktrace. You can refer Exception API here which explains how cause can be set to wrap exceptions.
Does Java or other libraries ever do this? Is it appropriate for my
use case ?
In many libraries, this pattern is followed, just to pin point, in spring-mvc, NestedServletException will be thrown by the container which will wrap the original exception with the cause. Yes, in your case, you can throw SendFailedException by setting the cause as SocketClosedException.
Also, if your message library is from third party, ensure that the 3rd party Exception classes don't spread across your project/classes, rather wrap/convert them into your own Exception classes so that your code is not tightly coupled with 3rd party Exception classes (even if you have to migrate from it).

Exception versus return code in DAO pattern

After reading a lot about the abusive use of exceptions in Java and how you should let an exception bubble up through the different layers of an application, I've come to a point where I don't know what I am supposed to do with the potential errors my application can have.
Basically, I have a webservice which uses the DAO pattern to access data in my database. All of the database actions can throw a SQLException.
As of today, I'm using a try catch to catch the SQLException and then thow a specific defined exception called ExceptionDAO that will be handle by the webservice to return a correct message to the users (a mobile application) of my webservice.
After reading a lot about how exception should be exceptional and should not be used in control flow, I've come up with a mixed understanding of what I should do to handle any errors:
Use return codes for anything that is likely to happen (e.g. username already exists) and therefore, to comply with the DAO pattern, pass my business objects as parameters instead. I could also use a specific pair which would return the code + the business object instead. The webservice would then use the return code to display a specific message.
Use checked exceptions for anything that I can't predict will happen and let them bubble up to the webservice to handle and return a message to the users. (e.g. SQLException that I can't predict : connection aborted)
Let unchecked exceptions bubble up aswell and display a sort of 404 error in this case.
I also had a look at the null pattern but I don't think it suits this particular situation really well.
I'm also concerned to not give too much information to the users, but rather useful and straight to the point information. Indeed, the messages returned by the webservice will be used by a mobile application to then display a message to the end-user.
I hope that I was clear enough about the problem I'm having, and I'm looking forward to your answers !
Return codes are suitable for C, which lacks exception handling among its features. For Java, please use exceptions, either checked or runtime, that's a matter of taste.
Personally, I hate checked exceptions, because they pollute my method signatures with information of border cases that might never occur. But maybe you want to be strict with the contract of your classes, even for such exceptional cases. If that's your case, then use checked exceptions. Otherwise, let your method signatures in peace and throw a runtime exception whenever you detect an exceptional case (such as an entity not found, entity already exists, etc).
Please note that ExceptionDAO is not a happy name. It appears to be a dao that handles exceptions. Maybe something like PersistenceException would be better.
Apart from that naming detail, I think your approach is on the right way, though not ideal. Ideally, you wouldn't need to do a try/catch for SQLExceptions inside every method that calls methods from your DAOs (or inside every method of your DAOs). Instead, a persistence exception translation mechanism would be much better. Spring, for instance, comes with one by default. Spring accomplishes this by proxying every DAO, and by letting its proxies perform a try/catch around every method invocation. Then, specific SQLExceptions with specific SQL error codes are translated to Spring's own DataAccessException hierarchy. So, in the upper layers, you would end up with a specific DataAccessException, but you wouldn't need to do a try/catch inside every method.
If you are already using Spring, then you have nothing to do, but if you aren't using it and have either many DAOs or many methods that might throw SQLExceptions, and all your DAOs implement an interface, then it might be worth the effort to implement a proxy that intercepts all the methods of your DAOs and performs a try/catch around them. Then, in this interceptor's catch block, you'd throw your ExceptionDAO (please rename it!) with a message that would depend on the original SQLException (and maybe on its SQL error code, too).
This approach has the advantage that you could handle all persistence exceptions in a single point of your program.
This very same concept could be applied to your web layer as well. Instead of letting every method of your endpoints handle your ExceptionDAO (don't forget to rename it!), you could create a proxy that intercepts every method call and perform a try/catch around it. You could then extract the message from the exception and send it in the response (or whatever you find suitable to do with it). Again, this is all based in Spring, this time, in Spring MVC Exception Handling mechanism. Here you could also handle unexpected exceptions, i.e. RuntimeExceptions and provide an appropriate message to your users.
The advantage, again, would be that you could handle all the exceptions that reached your web layer in a single point of your program.
Please see Proxy javadocs and this tutorial for further reference on Java's proxies.
I think you are missing an important option, which is the observer pattern.
In your DAO you can have this:
public interface OnExceptionInteractionListener {
public void onExceptionInteraction(String exceptionMessage);
}
I would have the DAO be something like:
public SomeDAO(OnExceptionInteractionListener listener, ...) {
}
and I would instantiate the DAO as
SomeDAO s = new SomeDAO(new OnExceptionInteractionListener() {
public void onExceptionInteraction(String exceptionMessage) {
}
}, ...);
So, if there is an exception caught then call the listener in the DAO and the next level up will handle it.
This is better performance than throwing exceptions, and better than return codes.
For more on this you can look at this answer, for other examples: https://stackoverflow.com/a/18585099/67566
I haven't tried it but I expect that lambda expressions would be useful for this also, if you are using Java8.
Return codes are very old-school. Ideally, you should do your insert in some sort of transaction that checks:
Lock username inserts
Is this username available?
3a. If so, insert and unlock
3b. If not, unlock and inform user
If that's not possible, then a return object wrapping the result if it was created successfully and response Enum with potential outcomes.

"try-catch" or "throws" to manage exceptions inside a Web service method?

Can you guys tell me the good way to manage exceptions in web services methods? (SOAP/REST/..)
Can you tell me the advantages and drawbackes in case of :
Using Try-Catch block and sending an error code. For example in case of REST :
try{
// something that triggers exception here...
return javax.ws.rs.core.Response.status(500).build();
}catch(..){
}
Using adding throws MyException in the prototype of the web service method
Thank you so much!
No real advantage or disadvantage. It depends on what implementation you want.
If its an internal implementation then i would throw back exception itself so that people calling webservice knows exact details of error.
If i am working web service for 3rd party, i would prefer returning code itself.
Using a Try-Catch you will catch any exceptions inside the method where the Try-Catch is. Using throws MyException you will throw the exception higher up in the hierarchy, meaning that the class/scope using your method will have to do something about the exception.
Generally these are good pointers:
catch an exception only if you can handle it in a meaningful way
declare throwing the exception upward if it is to be handled by the
consumer of the current
throw exceptions if they are caused by the input parameters (but
these are more often unchecked)
In your case I would probably use a Try-Catch and do something meaningful with the exception, maybe route the user to a error message.
In my opinion its always better to handle exception in Webservices with proper error codes. EvenIf you throw a custom exception finally it reaches the client as a SOAP fault exception. So it would be better to follow the following guidelines inorder to expose a better webservice:
Identify the possible errors and assign error codes and valid descriptions. This will help you to differentiate between validation errors, Data not found errors, runtime errors etc
Define your own custom error tags
<error>
<errorCode/>
<errorDesc/>
</error>
Populate this errors and send it back to the calling application. This will help them to handle the exceptions in their own ways
Its always better to pass meaningful errors as above rather than throwing the generic SOAP fault exception. You can notice this whenever you consume standard webservices

How to handle exceptions when writing a library (not an application) - Java

I'm currently writing an Java Wrapper for a RESTful web services API.
I'm now trying to clean up some of the exception handling, and not sure what approach to take. This is a tool intended to be used by Java programmers, so I can't really handle it the same way I would with a end-user application.
If I have a method (connection) that contains code that could throw exceptions, how do I get those exceptions to float up to the end-programmer? and is this even the way I should handle it, depending on them to catch the exceptions? etc...
I suggest you catch the exceptions from the underlying API (unless they really make sense to allow through), and throw a new exception which is more appropriate for your level of abstraction.
Use exception chaining if you don't feel like discarding the cause of the exception.
I think you should decide whether the existing type is specific to the implementation, or inherent to the library. For example, if it's a network related exception and you're obviously making a network-based API, I'd just let it propagate up. The caller needs to be aware of that sort of error anyway.
On the other hand, if it's a database-related exception which is only possible because for some bizarre reason you're looking up the WSDL in an embedded database, or something like that, that's clearly inappropriate for the caller to have to deal with - so catch it and wrap it in an exception which is more appropriate to your abstract level.
You will have to pass the exception to the user in any case since it's a library.
If you are not logging and are not planning to create custom exceptions, then you just don't have to handle the exception.
if you are logging, handle the exception and rethrow the exception.
if you have custom exceptions, make sure it have take exception a constructor parameter and then link the current exception to your current exception and then throw custom exception. This is required to maintain the useful stack trace information.
The question is how opaque you want your library to be.
Every exception type that you throw to your users should imply the user can do something about it. For example,
catch (ConnectionException e) {
disconnect();
connectAgain();
}
only works if your users have access to disconnect() and connectAgain(). If, however, you promise to provide all kinds of connectivity, your code should already have this logic, and if that fails, throw a generic WrapperException and be done with it.
Possibly a good approach for you would be declaring your own type of exception (and don't make it a RuntimeException), catching the exceptions you observe and throwing your exception instead.
I think its important what the API does, and in which context it is used.
If the API is part of your presentation/rendering layer, then I would prefer to always return something that is ready to be rendered, decorated, or written to the response stream.
If the API is meant to perform (non-rendering/UI related) processing, I would have no problem throwing up any exceptions outised the scope of the API logic.
If the API is designed well, these would be causes that are clearly beyond the control of the API, or logically beyond the scope of what the API "knows how to" or "should" handle, even if it could catch/control it.
When returning an exception to a "user" I prefer returning standard exceptions whenever possible rather than a single custom wrapper type.
Within my API implementation however, I use custom exception types frequently if they serve a clear and useful purpose.
just my 2 cents :)

Should RuntimeException be extended?

This is more of an OO design question.
So, I've got an UnsuportedLocaleException which will be used only on the initialization stage of an app. I've got two options:
Extend RuntimeException and leave it out there without any handling logics (acts as a config => apply defaults if wrong).
Extend an Exception and handle it (involves all the redundant coding etc.).
I like the first one more, but not sure if that'll be correct design.
Seems entirely reasonable to me. RuntimeException is a good base class for exceptions which calling code shouldn't try to "handle" - i.e. when they indicate the kind of failure which probably means that either the whole app or (possibly, for servers) the request should simply be abandoned.
The first one is fine. There are many exceptions that subclass RuntimeException.
There is several opinions here.
First (classic) says that in most cases you should use checked exceptions. In this case methods must either declare this exception as a part of its signature or catch it. This method has advantages that the interface is always clear and each layer care about its exceptions. But the method is pretty verbose. Sometimes your code becomes much longer, you have to right several try/catch statements instead of call a coupe of methods and write one if.
Other approach is to use runtime exceptions only. This philosophy says that you do not have to handle exceptions because you have nothing to do with them. In this case all exceptions are runtime and are caught and processed in one central module. For example Spring framework uses this approach.
So the answer is what are you developing. If this is stand alone library use checked well defined exceptions. If it is application or application framework you can use the runtime exceptions like Spring.

Categories