From a single method trowing two different custom exceptions based on the condition. While creating a custom exception passing two things one is an error message and another one is error code as a string. But I'm unable to get the error based on the error code. getting an error while calling processErrorCodes() method. Could anyone please help me in fixing this.
// BackgroundException is a custom EXCEPTION
public class BackgroundException extends Exception {
private static final long serialVersionUID = 4664456874499611218L;
private String errorCode="Unknown_Exception";
public BackgroundException(String message, String errorCode){
super(message);
this.errorCode=errorCode;
}
public String getErrorCode(){
return this.errorCode;
}
}
// Similarly I have InvalidException custom exception
public class MyExceptionTest {
public void methodTest(){
String policyId =null;
String policyNotification = null;
String policyStatus = null;
try {
if(policyNotification !=null) {
if(policyStatus!=null) {
if(policyId!=null) {
}
else{
throw new InvalidException("Policy ID Is Null","POLICY_ID");
}
}else{
throw new BackgroundException("Policy Status Is Null","POLICY_STATUS");
}
}
else{
throw new BackgroundException("Policy Notification Is Null","POLICY_NOTIFICATION");
}
} catch (BackgroundException | InvalidException e ) {
// TODO Auto-generated catch block
try {
processErrorCodes(e);
} catch (MyExcep e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.getMessage();
}
}
private static void processErrorCodes(Exception e) throws BackgroundException,InvalidException {
switch(e.getErrorCode()){
case "POLICY_NOTIFICATION":
System.out.println(e.getMessage());
throw e;
case "POLICY_ID":
System.out.println(e.getMessage());
throw e;
case "POLICY_STATUS":
System.out.println(e.getMessage());
throw e;
default:
System.out.println("Unknown exception occured, lets log it for further debugging."+e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
MyExceptionTest mt = new MyExceptionTest();
mt.methodTest();
}
}
I just want to handle those exceptions based on the error code.
You need a common superclass for all your custom exceptions, let say MessageCodeException, extending Exception and the accept this super class type as a parameter inside of your processErrorCodes method
public abstract class MessageCodeException extends Exception {
public abstract String getCode();
// you can have a same abstract method for message
}
public class BackgroundException extends MessageCodeException {
// ...
}
public class InvalidException extends MessageCodeException {
// ...
}
//and now the process method will look like
private static void processErrorCodes(Exception e) throws ... {
// ...
}
That's abvious that for current implementation you cannot access code field, because Exception class interface does not provide anything like this
BTW it seems to be very bad idea to create Exception driven business validation logic. Wouldn't it be better to create some kind of ValidationResult object with list (lists) of errors/warning/successes and to process such validation result at the end? The purpose of the Exception existence is not to control application flow, but to force user to provide some support for critical situations (or to handle somehow unexpected situations with RuntimeException)
Related
Assuming I have to read from a file, and then construct a java object out of it.
PersonData p = new PersonData();
p.setName(readTokenAsString());
p.setAge(AgeConverter.createFromDateOfBirth(readTokenAsString())); // this throws a checked exception if the date of birth is mal-formed.
//... a list of methods that throws exception as AgeConverter
Behavior I want: If one attribute has problem, just ignore it and keep process other attributes.
Solution I can think of:
try {
p.setAge1(...);
} catch (Exception e) {
//log and ignore
}
try {
p.setAge2(...);
} catch (Exception e) {
//log and ignore
}
//repeat for each attribute
Question:
Is there better way to do this to avoid repetition? Functional style maybe?
a) What's the best approach if I cannot modify PersonData class.
b) What's the best approach if I can rewrite PersonData class.
Given your current declaration, I would do it as follows.
Define a #FunctionalInterface to which you can pass your I/O logic:
#FunctionalInterface
public interface CheckedSupplier<T> {
T getValue() throws Exception;
}
Define an utility method that consumes the #FunctionaInterface:
public static final <T> T getValueWithDefault(CheckedSupplier<T> supplier, T defaultValue) {
try {
return supplier.getValue();
} catch (Exception e){
return defaultValue;
}
}
Use the utility method as follows:
PersonData p = new PersonData();
p.setName(getValueWithDefault(() -> readTokenAsString(), "default"));
p.setAge(getValueWithDefault(() -> AgeConverter.createFromDateOfBirth(readTokenAsString()), 0));
This should do the trick regardless of weather you want modify the PersonData class or not.
If you use Java 8 you can do something like this. Create your own functional interface with one method that throws Exception
public interface MyConsumer<T> {
public void process(T t) throws Exception;
}
And create a static method to use that interface
public static <T> void setAndLogException(T value, MyConsumer<T> consumer) {
try {
consumer.process(value);
} catch (Exception e) {
// log exception
}
}
And then using it like setAndLogException(AgeConverter.createFromDateOfBirth(readTokenAsString()), p::setAge);
You can also use solution provided by this: https://stackoverflow.com/a/28659553/6648303
This solution won't complain at compile phase about checked Exceptions.
It would be something like this:
public static void ignoringExc(RunnableExc r) {
try { r.run(); } catch (Exception e) { }
}
#FunctionalInterface public interface RunnableExc { void run() throws Exception; }
and then:
PersonData p = new PersonData();
ignoringExc(() -> p.setName(readTokenAsString()));
...
I'm designing a Java exception handling mechanism for a 2 component system {front-end, back-end}. The back-end will generate exceptions by using Exception classes for different error conditions. Front-end has to map those exception classes to a customer visible error code. This list of Exception classes can be pretty big and may continue to increase in size. What is the best way to map those Exception classes to customer visible error codes?
I could create a Map<Class, Integer> MAP_EX_CLASS_TO_ERROR_CODE and keep it updated, but is it the right/scalable way to map exceptions?
------- Edits after receiving initial set of answers, see Comments below ----
I want to represent similar types of exceptions, or exceptions that demand similar handling with one exception class. For e.g. UserExceptions can be:
RESOURCE_NAME_TOO_LONG
RESOURCE_NOT_FOUND
RESOURCE_NOT_OWNED
...
and InternalExceptions can be:
SERVER_UNAVAILABLE
REQUEST_TIMEOUT
...
If I make an enum for all these error codes, then is it still useful to implement the grouping? I wanted to do the grouping instead of defining one single class for checked exceptions because it'll force me to pay attention to the catch-ing of exceptions every time I add a new line of code that throws a different checked exception than existing code.
for e.g.
public enum ECodes {
RESOURCE_NAME_TOO_LONG(/*number*/0, UserException.class),
RESOURCE_NOT_FOUND(1, UserException.class),
RESOURCE_NOT_OWNED(2, UserException.class),
SERVER_UNAVAILABLE(3, InternalException.class),
REQUEST_TIMEOUT(4, InternalException.class);
// constructor and stuff
}
public class Prot1ExceptionMapper {
static Map<Ecode, /*CustomerCode*/Integer> MAP_EX_CLASS_TO_ERROR_CODE = new HashMap<>();
static {
MAP_EX_CLASS_TO_ERROR_CODE.add(Ecode.RESOURCE_NAME_TOO_LONG, PROT1_CUSTOMER_CODE1);
// Other mappings here
}
public static Integer map(Ecode ecode) {
// Lookup ecode
}
}
public class Prot2ExceptionMapper {
static Map<Ecode, /*CustomerCode*/Integer> MAP_EX_CLASS_TO_ERROR_CODE = new HashMap<>();
static {
MAP_EX_CLASS_TO_ERROR_CODE.add(Ecode.RESOURCE_NAME_TOO_LONG, PROT2_CUSTOMER_CODE1);
// Other mappings here
}
public static Integer map(Ecode ecode) {
// Lookup ecode
}
}
public class UserException extends Exception {
public UserException(ECodes ecode, String message) {
assert ecode.class == UserException.class;
}
}
public class InternalException extends Exception {
public InternalException(ECodes ecode, String message) {
assert ecode.class == UserException.class;
}
}
class DummyClass {
public void doFirstJob() throws UserException {}
public void doSecondJob() throws InternalException {}
}
class Protocol1MainClass {
public static void main(final String[] args) {
try {
doFirstJob();
doSecondJob();
} catch (UserException e1) {
// Do UserException specific stuff
throw Prot1ExceptionMapper.map(e1);
} catch (InternalException e2) {
// Do InternalException specific stuff
throw Prot1ExceptionMapper.map(e2);
}
Let me explain what I exactly expecting
I have a method like the following
public void removeByObject()
{
try {
DsrCollection dsrCollection = new DsrCollection();
dsrCollection. setNuId(180);
dsrCollectionRepository.remove(dsrCollection);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Here I want to check that the particular method removeByObject() executed successfully or not(also want to involve Assert.assertEqual(dsrCollectionRepository.remove(dsrCollection),??)). So for checking the condition what should be the actual value.
Or in a more specific way what object should appear in actual value place. My requirement is like if application failed to execute dsrCollectionRepository.remove(dsrCollection) it should return the assertError message
To make removeByObject() more testable you can simply extract the code in the try block into its own method. e.g.:
public class DsrCollectionRepositoryManager /* Or whatever your class is called. */ {
/* ... */
public void removeByObject() {
try {
removeByObjectOrThrow();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
protected boolean /* or whatever your return type is */ removeByObjectOrThrow() {
DsrCollection dsrCollection = new DsrCollection();
dsrCollection.setNuId(180);
return dsrCollectionRepository.remove(dsrCollection);
}
/* ... */
}
Now you can test removeByObjectOrThrow() and see if it throws an exception or not.
If you are trying to test it where removeByObject() is called on your behalf and/or you don't want to call removeByObjectOrThrow() directly then you can subclass your unit under test. e.g.:
public class DsrCollectionRepositoryManagerTest {
#Test
public void removeObjectSuccessful() {
boolean expected = true;
DsrCollectionRepositoryManager dsrCollectionRepositoryManager = new DsrCollectionRepositoryManager() {
#Override
protected boolean removeByObjectOrThrow() {
try {
boolean actual = super.removeByObjectOrThrow();
Assert.assertEquals(actual, expected);
return actual;
} catch (Exception cause) {
String message = "`removeObject` should not have thrown an exception but did";
throw new AssertionError(message, cause);
}
}
};
dsrCollectionRepositoryManager.removeByObject();
}
#Test
public void removeObjectUnsuccessful() {
DsrCollectionRepositoryManager dsrCollectionRepositoryManager = new DsrCollectionRepositoryManager() {
#Override
protected boolean removeByObjectOrThrow() {
super.removeByObjectOrThrow();
String detailMessage = "`removeByObject` should have thrown an exception but did not";
throw new AssertionError(detailMessage);
}
};
dsrCollectionRepositoryManager.removeByObject();
}
}
As I don't know the name of your unit under test nor the type of what you want to use assertEquals with I've made things up but the idea is the same: isolate the code you want to test and test it.
Does dsrCollectionRepository.remove(obj) return a value indicating whether the removal is successful or not? I'd recommend implementing the function so it does return a boolean on a successful removal of an object, otherwise you rely on exceptions to inform you of the failure of the function.
If it already returns a boolean value just assertTrue(dsrCollectionRepository.remove(dsrCollection);
If the failure of the function throws a known exception you can use the following annotation to test the function:
#Test(expectedExceptions = MyException.class), however you then rely on the fact that only that exception can be thrown while performing that function, which is problematic if someone adds an exception that can be thrown in implementation without your knowledge.
I have defined my own expection class:
public class ProduktException extends Exception {
public ProduktException(String msg){
//null
}
public static void throwProduktNotCreatedException() throws ProduktException {
throw new ProduktException("Cannot be created!");
}
public static void throwProduktNotDeletedException () throws ProduktException {
throw new ProduktException("Cannot be deleted!");
}
}
My Problem is I do not know how to throw them when I try:
try {
...
} catch(ProduktNotDeletedException e) {
e.toString();
}
That does not work... But I want to have these structure! What is wrong?
I appreaciate your answer!!!
UPDATE:
My Problem is, I do not want to create several Exception Klasses I want to have all Exceptions in one class. Is there possibly a solution for that?
If you need to differentiate between different kinds of exceptions, just create 2 different exceptions, maybe something like:
public class ProduktException extends Exception
{
public ProduktException(String msg){
//null
}
}
Then have:
public class ProduktNotDeletedException extends ProduktException
{
....
}
and
public class ProduktNotCreatedException extends ProduktException
{
....
}
Then you can catch one or the other, or both.
try {
...
} catch(ProduktNotDeletedException e1) {
e1.toString();
} catch(ProduktNotCreatedException e2) {
e2.toString();
}
EDIT:
For a single class what I mean is:
public class ProduktException extends Exception {
boolean notDeleted;
boolean notCreated;
public ProduktException(String msg){
super(msg);
}
public boolean isNotDeleted() {
return(notDeleted);
}
public boolean isNotCreated() {
return(notCreated);
}
public static void throwProduktNotCreatedException() throws ProduktException {
ProduktException e = new ProduktException("Cannot be created!");
e.notCreated = true;
throw e;
}
public static void throwProduktNotDeletedException () throws ProduktException {
ProduktException e = new ProduktException("Cannot be deleted!");
e.notDeleted = true;
throw e;
}
}
Then in your try/catch:
try {
...
} catch(ProduktException e) {
e.toString();
if(e.isNotCreated()) {
// do something
}
if(e.isNotDeleted()) {
// do something
}
}
You need to either catch ProduktException, e.g.
try {
...
} catch (ProduktException e) {
e.toString();
}
or declare subtypes, e.g.
public ProduktNotDeletedException extends ProduktException
You'll probably want to pass the message in the constructor up, so add the following in your constructor:
super(msg);
The Syntax given below.
class RangeException extends Exception
{
String msg;
RangeException()
{
msg = new String("Enter a number between 10 and 100");
}
}
public class MyCustomException
{
public static void main (String args [])
{
try
{
int x = 1;
if (x < 10 || x >100) throw new RangeException();
}
catch(RangeException e)
{
System.out.println (e);
}
}
}
What you could do if you don't want to create multiple subclasses of your ProduktException for each different type of exception you need to throw is to include a code in the exception which will let you know what is wrong. Something like this:
public class ProduktException extends Exception {
private Code exceptionCode;
private String message
public ProduktException(Code code, String msg){
this.message = msg;
this.exceptionCode = code;
}
//Getters and setters for exceptionCode and message
}
Code can be an enum so that your application can know that each code corresponds to a specific "problem" (product not created, product not deleted, etc.). You can then throw your exceptions like this
throw new ProduktException(Code.PRODUCT_NOT_CREATED,
"Error while creating product");
And when you catch it you can differentiate based on the code.
catch (ProduktException ex) {
if (ex.getExceptionCode().equals(Code.PRODUCT_NOT_CREATED)) {
...
}
else {
...
}
}
I cooked up a class ExceptionHandler<T extends Exception, OptionalReturnType> (see below) to eliminate some (what I view as) boilerplate code which was cluttering up actual implementation, while still providing a hook for explicit Exception handling if desired in the future. For the most part, in my application (essential a scientific computation), there is no such thing as recovery from exceptions - I need a log of the problem so I can fix it, but otherwise I'm just going to re-run once the problem is corrected.
Do other people do this (at least, in my specific application situation)? Is it dumb to do so (if yes, some explanation as to why would be nice)?
ExceptionHandler:
public abstract class ExceptionHandler<ExceptionType extends Exception,OptionalReturn> {
public abstract OptionalReturn handle(ExceptionType e);
//assorted boilerplate ExceptionHandling, e.g.:
public static <ET extends Exception> ExceptionHandler<ET, ?> swallower(final boolean printStackTrace, final String string) {
return new ExceptionHandler<ET,Object>() {
#Override public Object handle(ET e) {
if(printStackTrace) { e.printStackTrace(); }
if(string!=null && !string.isEmpty()) { System.err.println(string); }
return null;
}
};
}
public static <ET extends Exception> ExceptionHandler<ET, ?> swallower() { return swallower(false,null); }
}
example use (which I'm in the process of chopping down so I'm actually not writing quite so much):
public class Getter<From> implements Function<Future<? extends From>, From> {
private ExceptionHandler<InterruptedException,?> IEH;
private ExceptionHandler<ExecutionException,?> EEH;
public static final ExceptionHandler<InterruptedException,?> IEH_SWALLOWER = ExceptionHandler.swallower(true,"Returning null.");
public static final ExceptionHandler<ExecutionException,?> EEH_SWALLOWER = ExceptionHandler.swallower(true,"Returning null.");
private Getter() { this(IEH_SWALLOWER,EEH_SWALLOWER); }
private Getter(ExceptionHandler<InterruptedException,?> IEH, ExceptionHandler<ExecutionException,?> EEH) {
this.IEH = IEH;
this.EEH = EEH;
}
public static <T> Getter<T> make() { return new Getter<T>(); }
public static <T> Getter<T> make(ExceptionHandler<InterruptedException,?> IEH, ExceptionHandler<ExecutionException,?> EEH) {
return new Getter<T>(IEH, EEH);
}
#Override public From apply(Future<? extends From> from) {
if (from==null) throw new NullPointerException("Null argument in call with Getter.");
return getter(from, IEH, EEH);
}
private static <T> T getter(Future<T> src, ExceptionHandler<InterruptedException,?> IEH, ExceptionHandler<ExecutionException,?> EEH) {
try { return src.get(); }
catch (InterruptedException e) { IEH.handle(e); }
catch (ExecutionException e) { EEH.handle(e); }
return null;
}
}
which is used with the Guava libraries to do some embarrassingly-parallel calculations, and makes the actual Iterable transformation of Futures into something like Iterables.transform(futureCollection,Getter.make()) instead of tangle of inner-classes and exception handling.
I find the code honestly hard to follow and understand. It's full of static which is usually a bad sign in OO design and it's hard to follow with the generics.
Wouldn't something simpler like this work as well?
private static <T> T getter(Future<T> src) {
try { return src.get(); }
catch (InterruptedException e) { handle( "some text"); }
catch (ExecutionException e) { handle( e ) }
return null;
}
You can implement as many handle method as necessary in a base class (or in a static utility class) and use them in the catch block as necessary. Methods will be selected based on the signature, so if you want to print the text, you pass the string, if you want the stack trace you pass the exception (or both). Which leads to the combinations:
handle( String msg )
handle( Exception e )
handle( Exception e, String msg )
This solution has less if, which is usually a good sign as well.
But I have maybe missed a point, given that the code you published is just an excerpt of the whole code.
Have a look otherwise at this question, which is also related: Pluggable Error Handling Strategy
EDIT
If the solution I proposed above is too simple for your need, here are two other ways:
public class AbstractGetter<From> implements Function<Future<? extends From>, From> {
private abstract handleInterrupt( Exception e );
private abstract handleExecution( Exception e );
private static <T> T getter(Future<T> src ) {
try { return src.get(); }
catch (InterruptedException e) { handleInterrupt(e) }
catch (ExecutionException e) { handleExecution(e) }
return null;
}
}
And you implement the X concrete class that correspond the various exception handling strategies. That's essentially the template pattern.
You can still use delegation, but at a more coarse-grained level. Instead of providing individual handler, you provide a handler strategy. That's kind of variation of the strategy pattern then.
public interface ErrorStrategy
{
public void handleInterrupt(Exception e);
public void handleExecution(Exception e);
}
public class Getter<From> implements Function<Future<? extends From>, From> {
ErrorStrategy handler = new DefaultErrorStrategy(). // default one
public Getter<From>()
{
}
public Getter<From>( ErrorStrategy h )
{
this.handler = h.
}
private static <T> T getter(Future<T> src ) {
try { return src.get(); }
catch (InterruptedException e) { handler.handleInterrupt(e) }
catch (ExecutionException e) { handler.handleExecution(e) }
return null;
}
}
You can create the X error handling strategies that you need.
I think it's a good solution, but it could benefit from an ExceptionHandlerFactory and some xml files.