I would like to know that how can i trow customized block exception in java.i will explain it on following example.
#login
//Below code snippet do log in functionality.
mycode goes here
String name="abc";
if name.equals("ABC")
{
enter to system ...
}
Console Out Put
You have error on log in
#register
//Below code snippet do register functionality.
mycode goes here
let say in #login annotation there is a error from my code.java should throw it like a good readable way.The exception should be like regular exception and where it generate.i mean code block in this case it is log in.If register it should say u have an error in register code block.
Also i don't declare annotation on top of method.In my case there is no such a method and everything handle the annotations.
as a example
Student Class
class student{
#login
login related codes goes here
#View Result
view result related codes goes here
#logout
logout code goes here
}
As a example you can consider above class as a selenium script.in scripts we don't use any methods.i want to implement back end class(annotations) that gives and meaningful errors on happens in the related code block.(log in,view result,...)
when ever user write a new script he can reuse my annotation.
Actually this is a idea that i wanna implement.Because if i do like that it will be easy for my app users.so I would like to know that can it possible to do and if so how can i do it.If you know another way Please let me know your ideas.Thanks.
I'm not convinced I fully understand the question but if you're looking for creating a custom exception, you can do the following:
if name.equals("ABC") {
// do something
} else {
throw new CustomException("Name did not equal 'ABC'");
}
where the custom exception is defined as:
public class CustomException extends Exception {
public CustomException(String msg) {
super(msg);
}
}
And then wherever you need to handle the exception, it would look like:
try {
// do something that might throw a CustomException
} catch (CustomException ce) {
ce.printStackTrace();
// or do something more useful to handle the exception
}
And if you go this route, I would call it something other than CustomException, call it something that is relevant to the problem the exception pertains to, for example NameNotEqualException.
Related
Suppose I've got an endpoint in Dropwizard, say
#GET
public Response foo() { throw new NullPointerException(); }
When I hit this endpoint it logs the exception and everything, which is great! I love it. What I love less is that it returns a big status object to the user with status: ERROR (which is fine) as well as a gigantic stack trace, which I'm less excited about.
Obviously it's best to catch and deal with exceptions on my own, but from time to time they're going to slip through. Writing a try catch block around the entire resource every time is fine, but (a) it's cumbersome, and (b) I always prefer automated solutions to "you have to remember" solutions.
So what I would like is something that does the following:
Logs the stack trace (I use slf4j but I assume it would work for whatever)
Returns a general purpose error response, which does not expose potentially privileged information about my server!
I feel like there must be a built-in way to do this -- it already handles exceptions in a relatively nice way -- but searching the docs hasn't turned up anything. Is there a good solution for this?
As alluded to by reek in the comments, the answer is an ExceptionMapper. You'll need a class like this:
#Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
#Override
public Response toResponse(RuntimeException runtime) {
// ...
}
}
You can do whatever logging or etc. you like in the toResponse method, and the return value is what is actually sent up to the requester. This way you have complete control, and should set up sane defaults -- remember this is for errors that slip through, not for errors you actually expect to see! This is also a good time to set up different behaviors depending on what kind of exceptions you're getting.
To actually make this do anything, simply insert the following line (or similar) in the run method of your main dropwizard application:
environment.jersey().register(new RuntimeExceptionMapper());
where environment is the Environment parameter to the Application's run method. Now when you have an uncaught RuntimeException somewhere, this will trigger, rather than whatever dropwizard was doing before.
NB: this is still not an excuse not to catch and deal with your exceptions carefully!
Add the following to your yaml file. Note that it will remove all the default exception mappers that dropwizard adds.
server:
registerDefaultExceptionMappers: false
Write a custom exception mapper as below:
public class CustomExceptionMapper implements ExceptionMapper<RuntimeException> {
#Override
public Response toResponse(RuntimeException runtime) {
// ...
}
}
Then register the exception mapper in jersey:
environment.jersey().register(new CustomExceptionMapper());
Already mentioned this under the comments, but then thought I would give it a try with a use case.
Would suggest you to start differentiating the Exception that you would be throwing. Use custom exception for the failures you know and throw those with pretty logging. At the same RuntimeException should actually be fixed. Anyhow if you don't want to display stack trace to the end user you can probably catch a generic exception, log the details and customize the Response and entity accordingly.
You can define a
public class ErrorResponse {
private int code;
private String message;
public ErrorResponse() {
}
public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
}
... setters and getters
}
and then within you resource code you can modify the method as -
#GET
public Response foo() {
try {
...
return Response.status(HttpStatus.SC_OK).entity(response).build();
} catch (CustomBadRequestException ce) {
log.error(ce.printStackTrace());
return Response.status(HttpStatus.SC_BAD_REQUEST).entity(new ErrorResponse(HttpStatus.SC_BAD_REQUEST, ce.getMessage())).build();
} catch (Exception e) {
log.error(e.printStackTrace(e));
return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage())).build();
}
}
This article details Checked and Unchecked Exceptions implementation for Jersey with customized ExceptionMapper:
https://www.codepedia.org/ama/error-handling-in-rest-api-with-jersey/
Official Dropwizard documentation also covers a simpler approach, just catching using WebApplicationException:
#GET
#Path("/{collection}")
public Saying reduceCols(#PathParam("collection") String collection) {
if (!collectionMap.containsKey(collection)) {
final String msg = String.format("Collection %s does not exist", collection);
throw new WebApplicationException(msg, Status.NOT_FOUND)
}
// ...
}
https://www.dropwizard.io/en/stable/manual/core.html#responses
It worked for me by simply registering the custom exception mapper created in the run method of the main class.
environment.jersey().register(new CustomExceptionMapper());
where CustomExceptionMapper can implement ExceptionMapper class like this
public class CustomExceptionMapperimplements ExceptionMapper<Exception>
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 am writing piece of code in Java, which job is to parse configuration file. It's convenient for the end-users, because they can see and fix all parsing errors at once. But it's not very good for testing - instead of specific exceptions test function just expects very general ParsingError exception.
It's always a room for dark magic here, like testing private methods, but I don't want to go for it. Could you suggest better design solution for the case?
Why not throw just a single InvalidConfigurationException (I wouldn't use ParsingError - aside from anything else, I wouldn't expect this to be an Error subclass) which contains information about the specific problems? That information wouldn't be in terms of exceptions, but just "normal" data classes indicating (say) the line number and type of error.
Your tests would then catch the exception, and validate the contents was as expected.
The implementation would probably start off with an empty list of errors, and accumulate them - then if the list is non-empty at the end of the parsing code, throw an exception which is provided with that list of errors.
I have been here before. Exceptions are unsuitable. Instead you should provide a report inside your parser.
parser.parse();
if (parser.hasErrors()) {
for (ParserError error : parser.getErrors()) {
// Provide a report to the user somehow
}
}
Simple and easy to read. An exception should be thrown if there is an exception condition - e.g. there is no source data to parse, not because the parser found problems.
Why not use chained exceptions? You could build specific exceptions (say ParticularParsingError), then chain this with ParsingError and throw that back.
In your unit tests, use e.getCause() where e is a ParsingError.
First things first: ParsingError seems a strange name, ParsingException looks better (Error is a java.lang class that should not be caught)
You could add a list in your ParsingException and add a try-catch block in your test in which you test that your list contains what you expect.
For example you had:
#Test(expected=ParsingException.class)
public void test_myMethod_myTestCase(){
myMethod()
}
but then you would have:
public void test_myMethod_myTestCase(){
try {
myMethod()
}
catch(ParsingException pe) {
if (! pe.list.contains(anError)
|| ! pe.list.contains(anOtherError) ) {
fail();
}
}
}
I'm pondering on exception handling and unit tests best practices because we're trying to get some code best practices in place.
A previous article regarding best practices, found on our company wiki, stated "Do not use try/catch, but use Junit4 #Test(expect=MyException.class)", without further information. I'm not convinced.
Many of our custom exception have an Enum in order to identify the failure cause.
As a result, I would rather see a test like :
#Test
public void testDoSomethingFailsBecauseZzz() {
try{
doSomething();
} catch(OurCustomException e){
assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ, e.getFailure());
}
}
than :
#Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
doSomething();
}
when doSomethig() looks like :
public void doSomething throws OurCustomException {
if(Aaa) {
throw OurCustomException(FailureEnum.AAA);
}
if(Zzz) {
throw OurCustomException(FailureEnum.ZZZ);
}
// ...
}
On a side note, I am more than convinced that on some cases #Test(expected=blabla.class) IS the best choice (for example when the exception is precise and there can be no doubt about what's causing it).
Am I missing something here or should I push the use of try/catch when necessary ?
It sounds like your enum is being used as an alternative to an exception hierarchy? Perhaps if you had an exception hierarchy the #Test(expected=XYZ.class) would become more useful?
If you simply want to check that an exception of a certain type was thrown, use the annotation's expected property.
If you want to check properties of the thrown exception (e.g. the message, or a custom member value), catch it in the test and make assertions.
In your case, it seems like you want the latter (to assert that the exception has a certain FailureEnum value); there's nothing wrong with using the try/catch.
The generalization that you should "not use try/catch" (interpreted as "never") is bunk.
Jeff is right though; the organization of your exception hierarchy is suspect. However, you seem to recognize this. :)
If you want to check the raw exception type, then the expected method is appropriate. Otherwise, if you need to test something about the exception (and regardless of the enum weirdness testing the message content is common) you can do the try catch, but that is a bit old-school. The new JUnit way to do it is with a MethodRule. The one that comes in the API (ExpectedException) is about testing the message specifically, but you can easily look at the code and adapt that implementation to check for failure enums.
In your special case, you want to test (1) if the expected exception type is thrown and (2) if the error number is correct, because the method can thrown the same exception with different types.
This requires an inspection of the exception object. But, you can stick to the recommendation and verify that the right exception has been thrown:
#Test(expected = OurCustomException.class)
public void testDoSomethingFailsBecauseZzz() {
try {
doSomething();
} catch (OurCustomException e) {
if (e.getFailureEnum.equals(FailureEnum.ZZZ)) // use *your* method here
throw e;
fail("Catched OurCostomException with unexpected failure number: "
+ e.getFailureEnum().getValue()); // again: your enum method here
}
}
This pattern will eat the unexpected exception and make the test fail.
Edit
Changed it because I missed the obvious: we can make a test case fail and capture a message. So now: the test passes, if the expected exception with the expected error code is thrown. If the test fails because we got an unexpected error, then we can read the error code.
I came across this when searching how to handle exceptions.
As #Yishai mentioned, the preferred way to expect exceptions is using JUnit rules and ExpectedException.
When using #Test(expected=SomeException.class) a test method will pass if the exception is thrown anywhere in the method.
When you use ExpectedException:
#Test
public void testException()
{
// If SomeException is thrown here, the test will fail.
expectedException.expect(SomeException.class);
// If SomeException is thrown here, the test will pass.
}
You can also test:
an expected message: ExpectedException.expectMessage();
an expected cause: expectedException.expectCause().
As a side note: I don't think using enums for exception messages/causes is good practice. (Please correct me if I'm wrong.)
I made catch-exception because I was facing the same problem as you did, Stph.
With catch-exception your code could look like this:
#Test
public void testDoSomethingFailsBecauseZzz() {
verifyException(myObj, OurCustomException.class).doSomething();
assertEquals("Omg it failed, but not like we planned", FailureEnum.ZZZ,
((OurCustomException)caughtException()).getFailure() ;
}
I would like to get a second opinion on how to handle Exceptions within "events" (key input, screen update etc). In this case I have control over the event-sender.
So a module is set to handle an event (it implements a listener interface, and is registered against an event sender):
public void DefaultSet ( CardData oldDefault, CardData newDefault )
{
}
The event sender is simply:
for ( Enumeration e = listeners.elements(); e.hasMoreElements(); )
{
RetrieverListener thisListener = (RetrieverListener) e.nextElement();
thisListener.DefaultSet( oldDefault, newDefault );
}
So if/when something goes wrong in the receiver:
Should I try to cope with the exception there, and never throw anything back to the sender? Sometimes the listeners don't have the "context" to handle an error correctly, is that right?
Is it frowned on to throw an exception back to an event-sending module, to be handled in a documented way? e.g. "Throwing an IOException will result in a reset.. ". This seems non-standard from the javadocs I have read.
Should I just log and ignore the exception when something goes wrong & nothing can be done about it?
The Java convention is that listener methods do not throw exceptions. Obviously, programming errors might make a listener throw a RuntimeException, but there's no way the event source can recover from that because it will have left the program's objects in some unknown, maybe inconsistent state.
It is therefore up to the listener to catch checked exceptions and either recover from them (roll back a transaction, for example) or report them to some other object. I often use an ErrorHandler interface that looks something like:
public interface ErrorHandler {
public void errorOccurred(String whatIWasTryingToDo, Exception failure);
}
An event listener tells its ErrorHandler about errors that have occurred.
public class SomeClass implements SomeKindOfListener
private final ErrorHandler errorHandler;
... other fields ...
public SomeClass(ErrorHandler errorHandler, ... other parameters ... ) {
this.errorHandler = errorHandler;
...
}
public void listenerCallback(SomeEvent e) {
try {
... do something that might fail ...
}
catch (SomeKindOfException e) {
errorHandler.errorOccurred("trying to wiggle the widget", e);
}
}
}
I initialise event listeners with an implementation of this that handles the failure in whatever way makes sense at that point in the application. It might pop up a dialog, show a flashing error icon in the status bar, log an audit message, or abort the process, for example.
When nothing can be done about you should log and send a message to the user. If something goes wrong that may damage data or give wrong results if you can't recover you should close the application.
The usual approach is to ignore the issue. Listeners should not throw unchecked exceptions.
A better approach would be to catch and log RuntimeExceptions. These generally indicate a programming error. If a widget on the screen throw an NPE, then there is no reason why the rest of the window should not finish painting. The user can then save their data and restart or otherwise work around the issue. In the case of Errors it generally means that there is a serious situation, such as OutOfMemeory and catching will just result in thrashing. Nobody bothers doing this.