Tuesday, September 29, 2020

Java Basic Util - Exception Handler

 1 Create a functional interface:

package basic.util.function;


@FunctionalInterface

public interface IAction {

void run();

}

2 Create base exception to wrap raw exception

package basic.util.exception;


import java.text.MessageFormat;

import basic.util.log.Log;


public class BaseException extends RuntimeException {


private static final long serialVersionUID = 1L;

public final static String NotFound="{0}[{1}] cannot be found.";

public final static String NotLoaded = "{0}[{1}] cannot be loaded.";

public final static String Failed = "{0} {1}[{2}] is failed";

public final static String Wrong = "{0}[{1}] is wrong";

public final static String JsonExceptionScriptError = "Exception happened when parse Json string {0}";

public final static String ExceptionClassNotFound= "Class missing in {0}";

public final static String ExceptionInstantiationFailed= "{0} cannot be instantiation";

public final static String ExceptionIllegalAccess= "Cannot access {0}";

public final static String ExceptionIllegalArgument= "Argument {0} is illegal for {1}";

public final static String EExceptionAccessChannelFailed= "{0} to {1}:{2} failed";

private String[] parameters;

    public BaseException(String message, Throwable throwable, String... parameters) {

    super(message, throwable);

        this.parameters = parameters.clone();

    }

        

    public BaseException(String message, String... parameters) {

    this(message, null, parameters);

    }

    

    protected String[] getParameters() {

    return parameters;

    }


    public String getMessage() {

    String formatMessage = super.getMessage();

    try {

    MessageFormat format = new MessageFormat(formatMessage);

    formatMessage = format.format(getParameters());

    } catch(Exception inner) {

    // Ignore

    }

        return formatMessage;

    }

    

public static void throwException(Throwable throwable) {

throwException(throwable.getLocalizedMessage(), throwable);

}

public static void throwException(String message, Throwable throwable, String... parameters) {

logException(message, throwable, parameters);

throw new BaseException(message, throwable, parameters);

}

public static void throwException(String message, String... parameters) {

throwException(message, null, parameters);

}


public static void logException(String message, Throwable throwable, String... parameters) {

try {

MessageFormat format = new MessageFormat(message);


if (throwable != null)

Log.severe(format.format(parameters), throwable);

else

Log.info(format.format(parameters));

} catch (Exception inner) {

Log.severe(message, throwable);

}

}

}

3 Create business exception which used in business operation.

package basic.util.exception;

import java.text.MessageFormat;
import java.util.ArrayList;

import basic.util.resource.ResourceUtil;

public class BusinessException extends BaseException{

private static final long serialVersionUID = -6023367939226455780L;
private String messageKey;
private String[] pramaterKeys;
    public BusinessException(String message, String localisedMessage, Throwable throwable, String... parameters) {
        super(message, throwable, parameters);
        messageKey = localisedMessage;
ArrayList<String> list = new ArrayList<String>();
for(String param : getParameters()) {
list.add(param.replaceAll(" ", ""));
}
pramaterKeys = (String[]) list.toArray(new String[list.size()]);
    }  
    
    public BusinessException(String message, String key, String... parameters) {
    this(message, key, null, parameters);
    }   
    
    public String getLocalizedMessage() {
    String str = null;
try {
String msg = ResourceUtil.getString(messageKey);
String[] pramKeys = getFormatParameters();
MessageFormat format = new MessageFormat(msg);
str = format.format(pramKeys);
} catch (Exception inner) {
str = getMessage();
}
        return str;
    }

private String[] getFormatParameters() {
ArrayList<String> list = new ArrayList<String>();
for(String param : pramaterKeys) {
list.add(ResourceUtil.getString(param));
}
String[] pramKeys = (String[]) list.toArray(new String[list.size()]);
return pramKeys;
}
public static void throwException(String message, String localizedMessage, Throwable throwable, String... parameters) {
BaseException.logException(message, throwable, parameters);

throw new BusinessException(message, localizedMessage, throwable, parameters);
}
public static void throwException(String message, String localizedMessage, String... parameters) {
throwException(message, localizedMessage, null, parameters);
}
}

4 Create exception handler to wrap the execution of method and catch all exception on the entry.

package basic.util.exception;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Optional;
import java.util.function.Function;

import basic.util.function.IAction;
import basic.util.log.Log;
import basic.util.resource.ResourceUtil;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;

public class ExceptionHandler {
public static void runSafely(IAction action) {
try {
action.run();
} catch(Exception exception) {
handleException(exception);
}
}
public static Optional<Object> runSafely(Function<?, ?> func) {
Object result = null;
try {
result = func.apply(null);
} catch(Exception exception) {
handleException(exception);
}
return Optional.ofNullable(result);
}
private static void handleException(Exception exception) {
Log.severe(exception);
String title = ResourceUtil.getString("Exception.Handler.Title");
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText(exception.getLocalizedMessage());
alert.setContentText(exception.getMessage());

// Create expandable Exception.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
String exceptionText = sw.toString();

Label label = new Label("The exception stacktrace was:");

TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);

textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);

GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);

alert.getDialogPane().setExpandableContent(expContent);
alert.showAndWait();
}
}

No comments:

Post a Comment