For example, i created a exception that extends RuntimeException.
My exception has a new field called "code". I want to handle this exception in Oracle Service Bus process and retrieve this code to throws another exception with a XML structure that includes the code.
Is there a way to do that ?
I don't think that you will be able to retrieve just the "code". But certainly you can retrieve the details of the exception which will include your code.
Try it out.
Related
For my file (csv) upload endpoint, I check the file type using a method in my CsvHelper class:
private static String[] TYPES = {"text/csv", "application/vnd.ms-excel"};
public static boolean hasCsvFormat(MultipartFile file) {
return Arrays.stream(TYPES).anyMatch(file.getContentType()::equals);
}
And call it from service as shown below:
public void create(MultipartFile file) throws Exception {
if (!CsvHelper.hasCsvFormat(file)) {
throw new NotValidFormatException(...);
}
// ...
}
I created a custom exception for this called NotValidFormatException using #ControllerAdvice, but I am not sure if it is the most proper way for this.
My questions:
1. Should I create custom exception or custom validator as mentioned on this? But as I have not a model field, I need to use #Valid on the request and not sure if I can use that approach to verify file type (by calling my hasCsvFormat() method.
2. I used this approach for creating custom exception handling. If I wanted to use that approach for this scenario, should I create a separate class (e.g. NotValidFormatException) like NoSuchElementFoundException on that example? Or should I include a new exception method to the GlobalExceptionHandler class as a common exception type?
Based on your requirement, option number 2 is more suitable from my perspective.
You can create separate class for NotValidFormatException , annotate with ResponseStatus of your need & extend it with RuntimeException.
Now, your GlobalExceptionHandler is general purpose handler which perform actions once specific exception is thrown.
So you have to create method which should annotate with #ExceptionHandler(NotValidFormatException.class) in GlobalExceptionHandler .
Benefits of having separate class for NotValidFormatException is you can customize error message, can perform more operation within methods of that class.
If your requirement is minimal(like logging & returning response etc.) , then I would suggest to have only single ExceptionHandler method in GlobalExceptionHandler which will handle most of exceptions i.e. logging & returning response.
My understanding of these exceptions is if an object in the database that you are looking for doesn't exist or exists these gets thrown? But is it ok for myself to use when I want to handle different cases in MyServiceClass.
Is it bad practice to throw these exceptions or should I create my own Exceptions for let's say if a user dont exist in the database?
How does it work in a real production?
Thanks in advance!
You should only implement a custom exception if it provides a benefit compared to Java's standard exceptions. The class name of your exception should end with Exception.
But it’s sometimes better to catch a standard exception and to wrap it into a custom one. A typical example for such an exception is an application or framework specific business exception. That allows you to add additional information and you can also implement a special handling for your exception class.
When you do that, make sure to set the original exception as the cause. The Exception class provides specific constructor methods that accept a Throwable as a parameter. Otherwise, you lose the stack trace and message of the original exception which will make it difficult to analyze the exceptional event that caused your exception.
public void wrapException(String input) throws MyBusinessException {
try {
// do something
} catch (NumberFormatException e) {
throw new MyBusinessException("A message that describes the error.", e);
}
}
Try not to create new custom exceptions if they do not have useful information for client code.
And if you make a custom exception be sure to:
Document the Exceptions You Specify
Throw Exceptions With Descriptive Messages
Catch the Most Specific Exception First
Don’t Log and Throw
So I have this one question. Lets say we have classes: Main, Info, Cats, Food
Now, lets say that in main we create new object Info. In Info object we are saving list of Cats that have been created. Cats are being created and stored in Info class and Food is being created and stored in Cats class. Now lets say, that in Main class, I want to get specific Food object, which is stored in Cats class. So, in order to do so we do the following:
Info.getFood(name). Then in Info's getFood method we say Cats.getFood(name). Finally, in Cats class we have method getFood, in which we try to find Food object by its field "name". If we are unable to find such an element, we throw NoSuchElement exception rather than return an object. Here is my question:
If we throw exception in Cats class getFood method, should we catch that exception in Main class (where our interface is), in Info class (which is our system class) or in both of them?
Generally speaking, inside a method, if you can do something with the Exception being thrown (log an error, show an error message, make a different decision in your code, etc), then you should catch it. Otherwise, just throw it to the calling method.
As with many other coding practices, it all boils down to what you and your team agree on.
A concrete example which isn't related to your code, but which will show you how the decision process can be made. Assume the following code:
public MyConfiguration loadConfiguration () throws ConfigurationException {
MyConfiguration config = null;
try {
readConfigurationFromFile ();
// Parse configuration string
} catch (IOException ioex) {
throw new ConfigurationException (ioex);
}
return config;
}
private String readConfigurationFromFile () throws IOException {
String configuration = "";
// Read a file on disk, append data to the string.
return configuration;
}
In readConfigurationFromFile (), if an exception occurs while reading the file, you'll get an IOException. At this point in the code, there's no real action you can take, since this method only reads the configuration file, appends the data to a String, then returns it.
In loadConfiguration (), you can surround the call to readConfigurationFromFile () with a try/catch, and throw a more generic exception (ConfigurationException). Again, at this point, there's nothing you can do with the exception, except wrap it in a new exception which adds more context information to the original exception that was thrown.
Now assume that there's two flavors of your software: a GUI version, and a command-line version. If you are running the GUI flavor, then the method calling loadConfiguration could decide to show an error message to the user whenever a ConfigurationException is being thrown, so that the user knows that something happened. If you are running the command-line version, then maybe it would be more logical to add an entry to some error log with the exception that was caught.
The following site says "Most of the developers are embarrassed when they have to choose between the two options. This type of decision should not be taken at development time. If you are a development team, it should be discussed between all the developers in order to have a common exception handling policy."
http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions
It depends a lot on what you want to do after throwing that exception.
Say for instance that if all you want is to return any food object from any cat (and as you said 'Info' stores lots of cats) then you might have a catch in Info where you catch the NoSuchElement exception and then create some logic that moves onto the next Cat in Info to get its food! Finally if you exhaust all the 'Cats' in Info with no food found, you can throw another exception inside Info that you catch in Main that lets main know, "There's no food".
Again that's just an example. As people have said, it's not a "Always do this..." kind of answer. It depends greatly on what you need to do when handling that exception
I need to implement Exception management component, in Java.
Having this class :
public class Foo {
void connect(){
// some instructions here...
}
}
The specification document that I have it uses such expressions :
1. A_Exception can be received.
2. B_Exception can be catched as C_Exception<B_Exception> .
Edit :
What is the difference between a catched exception and a received exception? Some sample codes would be so helpful.
Thank you a lot!
Exception what will going to be handle is depends on the context. Importantly Checked Exception can be handle. You have to provide the context for this case. Normally NullPointerException not going to handle and will code the way not occur NPE.
I have 2 APIs from 2 different companies that allow me to communicate with their servers in order to process transactions. I am tasked with creating a generic interface to these APIs. I came up with something like this:
IServiceProvider <- ServiceProvider <- CompanyAServiceProvider
IServiceProvider <- ServiceProvider <- CompanyBServiceProvider
In CompanyAServiceProvider I am using the API that they offer to interface with their remote servers. This API from company A throws exceptions that are completely different from Company B's.
I can handle the exception locally but I don't really think that suites the situation.
public String purchase(String amount) {
try {
request = new Request( RequestIF.NEW_ORDER_TRANSACTION );
} catch ( InitializationException e ) {
//do something.
}
}
Or I can throw this exception to the caller:
public String purchase(String amount) throws Exception {
request = new Request( RequestIF.NEW_ORDER_TRANSACTION );
}
And let the caller handle just the Exception no matter what that exception is and no matter what API throws it.
How can I write an interface to 2 different APIs and keep it generic when I am dealing with 2 different sets of thrown exceptions. Am I dealing with this correctly? What would be the best choice?
In this case I create my own Exception sublcass and just wrap the actual exception. My API then exposes only my exception.
Think about what level of abstraction you are dealling with at the level of the calling functions. Presumably you don't want to expose details of the individual companies you are dealing with, and would prefer to deal with more generic concepts like Orders, PurchaceTransactions etc.
So the previous poster's advice is good: create a class like PurchaseException, which is a wrapper around the information you got back from the vendor's individual exception classes.
Another reason to handle the Exception locally and roll your own to throw downstream (when necessary):
There might be work (clean-up, retry, etc) that needs to be performed when a specific type of Exception is thrown that varies from vendor to vendor.