Standard for Exception Handling [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am writing an API, which will return some response, of course. There is a chance of the exception.
There are two options of response in the case of any exception:
Return some error message in response and let your consumers know what is going on.
Rather than error message return default response and don't let
consumers know If something bad is going on.
I know both approaches has its own pros and cons.
I just want to know, which one is the better approach to adopt and why?

An API should never leave its users wondering why they are not getting the expected response.
Errors forwarded to the users should be of at least two kinds:
errors due to invalid parameters passed to the API calls. This is an user error. If your API exposes HTTP, a 400 error is expected.
(unexpected) errors that happened on the API server although the supplied parameters were correct. If your API exposes HTTP, a 500 error is expected.
For user (400) errors, the API should provide the maximum details on the error so that the user can correct its input.
For server (500) errors, this is up to you, but the more details, the easier support calls will be to answer. Since this is likely a bug, a stacktrace is a big help for a developer to fix the issue.

1. Return some error message in response and let your consumers know what is going on.
You should try to extend the Exception class and define your own Exception Codes and then throw this custom exception object instead of SQLException or DataAccessExceptions.
Later you can also provide a basic manual for troubleshooting the errors based on the custom codes you defined.
It is a bad idea to show the SQL Trace/Exception to the end user as it may reveal some important information about your application such as SQL Queries, DB Schema and Table Names etc.
2. Rather than error message return default response and don't let consumers know If something bad is going on.
This is not a recommended approach as it will leave the users in state of a mystery of what's going wrong with the API and what they can do to fix it.

Related

Should I use GET or POST for an endpoint passing or returning anything in Spring Boot? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
I have a mail sender method in my Spring Boot app and when I defining related endpoint in the Controller, I could not be sure what is the most proper request for that.
As I do not pass any parameter and the method does not return any content, I am not sure POST or GET is suitable for this. So, which request should I use?
You need to think of the intention behind the request. Since it is a MAIL request, you are intending to perform some action with this. Hence it would be advisable to use the POST method.
Here is a reference to the existing methods:
GET : The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
POST : The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server.
Here is the Link for the MDN docs for this.
When you think about the future, there might be some data that you need to send for MAIL which you might not need now, hence using POST makes most sense.
Premised that the choice depends on your personal opinion and habit as developer, and on the specific purpose of your application.
However, in your specific case, I would follow the below logic:
Request is about "retrieving" email -> GET method is better
Request is about "sending" email -> POST method is better
So the logic is the following: as long as I ask the server to only "retrieve" information and I am not going to send any information to the server (i.e: coming from a form), i will always use GET.
On the other hand, when you also need to pass info to the server and it needs to apply some logic/operation, which might also affect some database, in that case the POST method works better.
Hope that answer your questions. Feel free to add more details, I will strive to help you further.

Is it bad practice to add CR/LF's to logging messages to improve readability [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
We have a method which we use to log java exceptions in a log file. The method allows the caller to pass variables they wish to be shown in the log message for debugging purposes and uses inserts blank lines and tabs to make the message stand out and be more readable.
However, all of the recommendations I see to prevent Log Forging attacks recommend stripping all of the CRLF's out of the logging message.
Is it considered bad practice to have CRLF's in a logging message? This method is only used internally and any user supplied information can be sanitized before being passed to the method.
generally - yes.
while this seems a nice feature at first glance, you should consider the following potential complications:
depending on exactly how this is implemented, if you hand the underlying logging framework multiple lines as multiple logging invocations your statement could get interleaved with other concurrent logging statements, making the resulting log less readable
various log-parsing tools tend to assume one line == one statement. most know how to account for exception stack traces (that are multi line) but not much beyond, so you may find yourself having to delve into things like ELK stack / loggly configs to teach it about your fancy multiline statements.
complications around terminals with different widths (if youre printing to console)
I think the real problem is that you're tightly coupling the message you output with the medium you're expecting it to be stored in (a plain-text file). I'd recommend looking into structured logging frameworks, and more powerful "Sinks" for your structured logs to go to, so you can analyze your logs without relying on message-formatting tricks.

How to divide large Http Response [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have Spring Boot RESTful service API. The consumers are other applications. One of the app's controller returns up to 1 000 000 strings on request.
What is the best practice of splitting such responses in Spring applications?
Update:
I figured out the response is needed for developer's needs and would be executed only once. So it's better to create the script for this operation.
Thanks for the answers.
Here is a good example to use multi part request in spring boot: https://murygin.wordpress.com/2014/10/13/rest-web-service-file-uploads-spring-boot/
However, I would prefer to think about your problem from an architectural point of view.Why should the rest returns such a huge response?And is it necessary to really returns all those results? There are a few factors that might help me to give a better answer.
This is the kind of situation when there is always a trade off.
1)The basic question is, can't you provide additional(they don't have to be mandatory, they can be optional parameters) to reduce the amount of returned results?
2)How frequent does your data change?If they don't change pretty often(let's say once a day) then you can introduce a sort of paging mechanism so you return only a segment of the result. From your side , you can introduce a caching mechanism between your business logic layer/data base and the rest client.
3)If your data are changing frequently(like you are providing list of flight prices), then you can introduce a caching layer per client ID. You can cache the results from your side and send it to the client divided into several requests. Of course you will have to add a time stamp and expiry date for each cached request or otherwise you will face memory issues.
4) This leads us to another question, where does the pain comes from?
Does the application clients complain about not being able to handle the amount of data they receive? Or do they complain from your response time of your service?Or are you having performance issue on your server side?

Reusing an Exception class for a different purpose [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it in good practice to use an exception for a different purpose than the intended one, for the name? For example, I wanted an exception something along the lines of "Already exists" and I found the exception "EntityExistsException." The name was great, but it seems it was intended for the EntityManager. Is it okay to use the class, or should I create my own?
Read the documentation. Anyone unfamiliar with your code will look at the exception, and either know its documentation or go and read it.
In this case, the documentation says the exception is
thrown by the persistence provider when EntityManager.persist(Object)
is called
so if it is thrown in other circumstances by your code then your code isn't compatible with the Java API and has a bug.
I would tend to either use or subclass IllegalStateException for your case, since that is a general purpose exception, is widely used, and the state of 'the thing already existing' falls within its specification. If I expected that client code would handle the 'already exists' state differently than other failing states, then I would subclass it, otherwise I wouldn't.
This issue is probably best answered on a case by case basis, since "different purpose than the intended one" is a little bit vague to offer a complete suggestion on.
In your case, it may come down to a matter of taste. Personally, unless your already exists exception needs are related to the persistence layer, I would advise against reusing the exception from that package since it is easy to make a new exception and will not confuse any future developers or code that may infer the exception is being passed on from the underlying implementation.

Which type of exception should be generalized or created a base class for in a Java architecture [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As a team lead which type of exception should I create a base class for in my architecture - checked or unchecked ? My team would start development in a few weeks and I want the architecture to be conducive to them for usage. Any reasons around that would also help.
That depends on the situation.
You use checked exceptions (extend Exception) for things that can go wrong regardless of the input the caller of the method passes. For example, network connections; you can make an HTTP GET request by calling client.get("google.com"); and everything goes well, two minutes later you call once again client.get("google.com"); and then you get an exception because of a network error. As you can see, here you called the same method passing the exact same input "google.com", yet you can get an exception at anytime. Therefore, you must force the caller to catch the exception by making it "checked", so that they handle those cases in which a network error occurs.
You use unchecked exceptions (extend RuntimeException) when the error happens because of some sort of invalid input by the caller of the method. For example, you have the method Integer.parse(String);. The method cannot work properly if you pass a null string here, so you throw an exception if that happens. This case, you should not force the caller to catch it, because the caller is responsible of passing the right input.
Overall: let the them decide, start with a short discussion. Helps people getting to know each-other.
I'd avoid checked exceptions: since they need to be explicitly catched, the catch block could become part of the normal program flow. Increases complexity and thus chance of introducing bugs.
Also don't use custom exceptions when possible, use existing exceptions like IllegalArgumentException. Avoid NullPointerExceptions by never returning null. Furthermore try to use something like bean-validation. That can save a lot of errors in your code caused by invalid (combinations of) arguments. And last but not least, failing fast is better then making your own faulty retry logic.

Categories

Resources