need to make httpstatus in opensource httpclient throw an exception - java

I have a a misbehaving calling application which I dont have the source for, which confronted with a non 200 http status- quietly logs an error/information message...
I need to be able to make it actually exit with some kind of error message. happen to know that it does catch some exceptions.... so this is my strategy
replace some part of the http client code with one that throws an exception and then let the exception bubble up to this app, where upon I expect it to exit...
Is there any other way/better to do this ? if not better simply suggestions of alternatives also welcome.
Thanks

That seems like a reasonable approach. You could also try using an aspect - if you use load-time weaving, you can add aspects to the client application at the point where you want it to throw an exception (though without the source code it will be tricky to work out the exact pointcut).

Related

Is it good practice to raise an exception on "bad requests" in an http API - in contradiction to (Java) best practice

Normally I try to use exceptions only for "exceptional" conditions ("Effective Java ", Issue 69). My personal interpretation is:
if I hit a condition in a specific part in code (normally a method or constructor) where I can't give a meaningful answer or outcome anymore I throw an exception and whoever called the piece of code has to handle it.
In the special case of HTTP endpoints I can always give a meaningful answer - a response with a status code.
Handling bad requests thus belongs to normal program flow of endpoint methods and should not raise new exception.
E.g. an endpoint that returns a resource should just return 404 in case the resource is not found. In my opinion it would be bad practice to raise a "SomethingNotFoundExcetion" (that could be handled by an error handler and create 404 response)
My question is: It is bad practice to use Spring Boot's error handling mechanism for bad requests (4xy) that relies on exceptions to create specific HTTP responses. (It is really fine for all uncovered errors yielding 500)
(I am just writing a review of code and I am not sure if I should suggest to not use error handler for "normal" API interaction)
Answer/Comment to current answers
It seems that the most of you missed the important part of my reasoning:
(citing Effective Java, Item 69):
Use exceptions only for exceptional
conditions ...
this reasoning:
• Because exceptions are designed for exceptional circumstances, there is little
incentive for JVM implementors to make them as fast as explicit tests.
• Placing code inside a try-catch block inhibits certain optimizations that
JVM implementations might otherwise perform.
The main point for me is:
A well-designed API
must not force its clients to use exceptions for ordinary control flow.
Especially in case of rest API. It should be easy to use any API in a way to avoid exceptions at all. This means for me. No correct (defined e.g. in Open API) usage of a Rest API should raise an exception.
To put another point: The standard for SOAP (another http based API stuff) forbids to use "SOAP fault" for correct (defined by WSDL) requests.
For me raising exception in remote APIs on not exceptional cases are even worse then in classic API (via dependency).
It depends on your project, it's really a matter of opinion/architectural decision. I'd say either-or.
The advantage of using specific Exceptions and then using a Spring handler to map them is that it removes the tedious construction of responses with the correct code from the actual application logic code (it's not dissimilar from aspects in that respect): just throw the correct exception and be done with it.
OTOH, the distance to the error handling code means that 1. if something doesn't work, it may be difficult to track down the issue 2. you need to know what exceptions to throw, and that is not immediately obvious and needs to be documented well.
It is not a bad practice, but a matter of architectural decision. It could be good to have an error handler that will produce a 4xx response and will do some additional error handling work, such as logging, and/or sending a notification by mail or queue or (like in my project) write errors in the table so they could be reviewed by user using GUI component of an application and may be even edited and re-submitted if it makes sense. It also unifies the error handling to a single code (code re-use). But if you really just need to send a 4xx response and nothing else, then its OK not raise exception and just do it in your code. Raising exception is expensive performance-wise and shouldn't be done just for the sake of raising exception alone. But in this particular case my opinion is to use Exception/Spring boot Error handling mechanism

How to deal with wrong ids of resource in REST API?

I have the following method in my service layer.
public void delete(int candidateId) {
candidateRepository.delete(candidateId);
}
Pretty basic, now this method is used by the web layer which RESTful architecure is applied.
The URL that will trigger this method is:
DELETE /candidates/{id}
How should I deal with wrong ids given by the clients that use the REST API in the service layer? I know the HTTP response would be 4xx but how should I communicate that the id is invalid between the service and web layer?
Should I use a unchecked exception since this is a condition that my application is unable to recover from? The fault barrier (Spring exception handler) will deal with it.
Or should this be a checked exception since it is possible that clients give wrong ids?
I am using the latest Spring technology if that matter
If it is possible that clients give wrong ids, then they will give wrong ids. And this is a condition that your application should be able to recover from.
I would return a checked exception for this. But introducing a checked exceptions can sometimes mean changes throughout different layers of the application, because, for example, the signatures of many methods would need to be changed to add the "throws" clause (breaking OCP). In case that gets overcomplicated some people (like in Robert C. Martin's "Clean Code") recommend using unchecked exceptions. I would say it's up to you what to return as long as the exception has a meaningful description.
Firstly, you need to decide how your REST API will handle exceptions. There are multiple, equally valid solutions to this.
When designing an API, you pretty much have to assume that whatever can go wrong, will go wrong. Client applications will pass incorrect parameters, use incorrect formats, etc.; your application should expect this, and handle it gracefully.
Using exceptions to communicate business logic is not particularly readable, and may have performance implications. It really doesn't scale beyond very simple cases - imagine that the business logic for "delete" might need to include failures for "record not found", "record has dependent relationships", "record protected", "record archived" etc.
Instead, I would design the application to pass explicit status information back and forth, and translate this into whatever RESTful error handling you use.

"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

Java Throwing exceptions vs returning response in catch

I know a lot has been discussed around exception handling, however I need some advice specific to my situation.
I am currently working on a Spring MVC application with Controller->Services->DAO layers. The service classes catch mainly two kinds of exceptions HibernateException and IOException.
HibernateException because service needs to perform rollback if a transaction did not succeed and IOException since it is an unchecked exception and needs to be caught or thrown and I prefer the first option.
Now what would be a better way of handling these further up in the stack :
Should I rethrow these exceptions to the controller and in the
ExceptionHandler of the controller send a HTTP error-code 500
Or in the catch block create the normal JSON response object, setting status=failure and the appropriate error message and return this to the Controller?
Exception Handling convensions:
There is a saying that, best way of handling Exception is not to handle it!
For Spring's convention of controller<->service<->dao layers, Exception handling mechanism is known as Bubble up. Any exception occurs in the dao or service layer, you should pop it up to the controller layer (by adding throws XXXException in dao and service layer's method signature, is the most common way). Only controller layer should handle Exceptions.
Here is a nice tutorial of how you can handle exceptions for REST with spring.
Send HTTP Status code 500 or JSON object with status:
Sounds like you are writing API with Spring MVC. Look, when you are writing API's you should follow the proper conventions. It is Globally accepted that for internal server errors you send HTTP response with code 500, that means internal server errors.
There are number of causes for what you should not send JSON response in this case. One of the main cause is the implicit assumption of your API client. That is HTTP response with code 200 with a JSON object means every thing went normal. And thus the client side business logic may reflect that assumption which is wrong eventually.
Here you can see some API error code conventions for some well-known organizations:
twitter
LinkedIn
Facebook Graph API
I assume that you have not come so far yet as to create a client and therefor can pick 100% for yourself.
If so I would also recommend to use 1, for the main reason that using the correct status codes can go a long way in your API, as well as it's a very easy solution to your problem. You can write some neat code for your error handling.
Another major reason why you should use your first point is because you can easily re-use the error handling for other APIs, resources or webapps.
For example an enum with all your errors, and what status code you consider them to be, and you can also include what log level you want them to be.
public enum ExceptionMapping {
IllegalArgumentException(IllegalArgumentException.class, 400, LogLevel.ERROR),
If your goal is to build a neat API for unknown clients I would recommend reading more about REST level 3 (http://martinfowler.com/articles/richardsonMaturityModel.html) where you includes hypermedia links to create an API which allows the client to "browse" your full API. It's more work for the client since they have to be smarter but it can provide you with very nice features such as breaking a large part of your API without the client even noticing.

How to do Exception Handling in Wicket

I've read that wicket can't throw Checked exception. how to deal with this? What is a good way to implement exception handling in Wicket spring based application?
Mac
What do you mean, "Wicket can't throw". [citation needed] :)
Perhaps you read somewhere that wicket will not pass an exception to the servlet container in the default configuration?
I usually wrap specific components' methods with a try and change the page appropriately in catch, i.e. telling the user that something went wrong.
Update:
And also, you have the error(), warn() etc. in every Component which works with Feedback stuff. See here.

Categories