This blog will give you an overview on how you can successfully deal with unhandled Runtime exceptions in an ADF application.
This will give you an idea of:
#1. Catch unhandled exceptions :
Create a class "MyExceptionHandler" which extends : oracle.adf.view.rich.context.ExceptionHandler. Override handleException() method.
public void handleException(FacesContext facesContext, Throwable throwable, PhaseId phaseId) throws Throwable {
// this method is going to create a separate file with stacktrace and thread dumps
writeException(throwable);
// redirect to error page
redirectToErrorPage(facesContext);
}
Create a folder "services" inside : ViewController\src\META-INF and then create a file named "oracle.adf.view.rich.context.ExceptionHandler".
In the file, add the absolute name of your custom exception handler class (package name and class name without the “.class” extension)
For more info check : https://blogs.oracle.com/jdevotnharvest/entry/extending_the_adf_controller_exception_handler
I had some problems adding this folder in the generated EAR file. So please check the ViewController deployment profile. You need to add the project source path also as a contributor to your WEB-INF/classes folder.
#2. Log file with stacktrace and thread dumps :
Either you can write this logic inside "MyExceptionHandler" class or inside a Singleton object. So that we can make sure when we report the problem, we have an unique id to identify the log file.
I preferred writing the logic in "MyExceptionHandler" class. The relevant contents of the class is below.
There is an inner class(IncidentContext) also to track the unique id of the exception incident.
private static final ThreadLocal<IncidentContext[]> incidentContext = new ThreadLocal<IncidentContext[]>() {
@Override
protected IncidentContext[] initialValue() {
return new IncidentContext[1];
}
};
private void writeException(Throwable t) {
IncidentContext context = incidentContext.get()[0];
if (context == null) {
context = new IncidentContext("No additional context");
}
StringBuilder incident = new StringBuilder();
Calendar calendar = Calendar.getInstance();
String incidentID = String.format("%s-%2$tY%2$tm%2$td_%2$tH%2$tM%2$tS", context.identification , calendar);
String incidentFile = String.format("incident-%s.log", incidentID);
incident.append("------------------------------------------------------------------------------------------------------------------\n");
incident.append(format(" Filename : %s\n", incidentFile));
incident.append(format(" Date : %1$tB %1$te, %1$tY\n", calendar));
incident.append(format(" Time : %1$tl:%1$tM:%1$tS %1$tp\n", calendar));
incident.append("------------------------------------------------------------------------------------------------------------------\n\n");
incident.append(format(" Unexpected error context: %s\n\n %s\n", context.text, ExceptionUtils.getFullStackTrace(t)));
incident.append("------------------------------------------------------------------------------------------------------------------\n\n");
incident.append(format(" ** THREAD DUMP:\n\n%s\n", dumpThreads()));
incident.append("------------------------------------------------------------------------------------------------------------------\n");
incident.append("[END]\n");
ExceptionWriter.getCurrentInstance().setExceptionID(incidentID);
String filePath = ExceptionWriter.getCurrentInstance().getFilePath();
File f = new File(filePath, incidentFile);
boolean traceWritten = false;
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(incident.toString().getBytes());
fos.flush();
traceWritten = true;
} catch (FileNotFoundException e) {
logger.error("The original exception was :" + incident.toString(), e);
} catch (IOException e) {
logger.error("The original exception was :" + incident.toString(), e);
}
}
private String dumpThreads() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);
StringBuilder stack = new StringBuilder();
for (ThreadInfo info : infos) {
stack.append(info.toString());
}
return stack.toString();
}
private final static class IncidentContext {
public static long incidentCount = 1L;
public final String identification;
public final String text;
IncidentContext(Long id, String txt) {
identification = id.toString();
text = txt;
}
IncidentContext(String txt) {
identification = String.format("#%d", incidentCount++);
text = txt;
}
}
You also need to create a session scope bean. Which will be used in the error page to report the exception ID, so that the end user can report this to the system administrators.
Register it in the adfc-config.xml.
<managed-bean id="ew1">
<managed-bean-name id="ew2">ExceptionWriter</managed-bean-name>
<managed-bean-class id="ew3">my.exception.ExceptionWriter</managed-bean-class>
<managed-bean-scope id="ew4">session</managed-bean-scope>
</managed-bean>
The class should look like :
public class ExceptionWriter {
private String filePath;
private String exceptionID;
public static ExceptionWriter getCurrentInstance() {
return (ExceptionWriter) JsfUtils.getExpressionValue("#{ExceptionWriter}");
}
public String getFilePath() {
filePath = getDirectory();
return filePath;
}
// Reads the folder to write the log file from web.xml context-param.
// default folder : D://incident
private String getDirectory() {
String directoryName = ContextUtil.getContextProperty(FacesContext.getCurrentInstance(), "incidentFilePath");
File theDir = new File(directoryName);
if(theDir.exists() &&theDir.isDirectory()) {
return directoryName;
}
return "D://incident";
}
public void setExceptionID(String exceptionID) {
this.exceptionID = exceptionID;
}
public String getExceptionID() {
return exceptionID;
}
}
#3. Redirect the user to an static error page :
private void redirectToErrorPage(FacesContext facesContext) throws IOException {
ExternalContext ectx = facesContext.getExternalContext();
ectx.redirect("pages/common/Error.jspx");
}
The Error.jspx:
<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<f:view>
<af:document id="d1">
<af:form id="f1">
<af:panelHeader text="The server is unable to respond at this time. Thank you for your patience." id="ph1">
<af:outputFormatted value="An unexpected error occurred, please contact System Administrator with the following number : #{ExceptionWriter.exceptionID}" id="of2"/>
<!-- PUT a navigation to the HOME page of your application here -->
</af:panelHeader>
</af:form>
</af:document>
</f:view>
</jsp:root>
#4. Results :
This will give you an idea of:
- How to catch the unhandled exceptions.
- Write a separate log file with stacktrace and thread dumps.
- Redirect the user to an static error page
#1. Catch unhandled exceptions :
Create a class "MyExceptionHandler" which extends : oracle.adf.view.rich.context.ExceptionHandler. Override handleException() method.
public void handleException(FacesContext facesContext, Throwable throwable, PhaseId phaseId) throws Throwable {
// this method is going to create a separate file with stacktrace and thread dumps
writeException(throwable);
// redirect to error page
redirectToErrorPage(facesContext);
}
Create a folder "services" inside : ViewController\src\META-INF and then create a file named "oracle.adf.view.rich.context.ExceptionHandler".
In the file, add the absolute name of your custom exception handler class (package name and class name without the “.class” extension)
For more info check : https://blogs.oracle.com/jdevotnharvest/entry/extending_the_adf_controller_exception_handler
I had some problems adding this folder in the generated EAR file. So please check the ViewController deployment profile. You need to add the project source path also as a contributor to your WEB-INF/classes folder.
#2. Log file with stacktrace and thread dumps :
Either you can write this logic inside "MyExceptionHandler" class or inside a Singleton object. So that we can make sure when we report the problem, we have an unique id to identify the log file.
I preferred writing the logic in "MyExceptionHandler" class. The relevant contents of the class is below.
There is an inner class(IncidentContext) also to track the unique id of the exception incident.
private static final ThreadLocal<IncidentContext[]> incidentContext = new ThreadLocal<IncidentContext[]>() {
@Override
protected IncidentContext[] initialValue() {
return new IncidentContext[1];
}
};
private void writeException(Throwable t) {
IncidentContext context = incidentContext.get()[0];
if (context == null) {
context = new IncidentContext("No additional context");
}
StringBuilder incident = new StringBuilder();
Calendar calendar = Calendar.getInstance();
String incidentID = String.format("%s-%2$tY%2$tm%2$td_%2$tH%2$tM%2$tS", context.identification , calendar);
String incidentFile = String.format("incident-%s.log", incidentID);
incident.append("------------------------------------------------------------------------------------------------------------------\n");
incident.append(format(" Filename : %s\n", incidentFile));
incident.append(format(" Date : %1$tB %1$te, %1$tY\n", calendar));
incident.append(format(" Time : %1$tl:%1$tM:%1$tS %1$tp\n", calendar));
incident.append("------------------------------------------------------------------------------------------------------------------\n\n");
incident.append(format(" Unexpected error context: %s\n\n %s\n", context.text, ExceptionUtils.getFullStackTrace(t)));
incident.append("------------------------------------------------------------------------------------------------------------------\n\n");
incident.append(format(" ** THREAD DUMP:\n\n%s\n", dumpThreads()));
incident.append("------------------------------------------------------------------------------------------------------------------\n");
incident.append("[END]\n");
ExceptionWriter.getCurrentInstance().setExceptionID(incidentID);
String filePath = ExceptionWriter.getCurrentInstance().getFilePath();
File f = new File(filePath, incidentFile);
boolean traceWritten = false;
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(incident.toString().getBytes());
fos.flush();
traceWritten = true;
} catch (FileNotFoundException e) {
logger.error("The original exception was :" + incident.toString(), e);
} catch (IOException e) {
logger.error("The original exception was :" + incident.toString(), e);
}
}
private String dumpThreads() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = bean.dumpAllThreads(true, true);
StringBuilder stack = new StringBuilder();
for (ThreadInfo info : infos) {
stack.append(info.toString());
}
return stack.toString();
}
private final static class IncidentContext {
public static long incidentCount = 1L;
public final String identification;
public final String text;
IncidentContext(Long id, String txt) {
identification = id.toString();
text = txt;
}
IncidentContext(String txt) {
identification = String.format("#%d", incidentCount++);
text = txt;
}
}
You also need to create a session scope bean. Which will be used in the error page to report the exception ID, so that the end user can report this to the system administrators.
Register it in the adfc-config.xml.
<managed-bean id="ew1">
<managed-bean-name id="ew2">ExceptionWriter</managed-bean-name>
<managed-bean-class id="ew3">my.exception.ExceptionWriter</managed-bean-class>
<managed-bean-scope id="ew4">session</managed-bean-scope>
</managed-bean>
The class should look like :
public class ExceptionWriter {
private String filePath;
private String exceptionID;
public static ExceptionWriter getCurrentInstance() {
return (ExceptionWriter) JsfUtils.getExpressionValue("#{ExceptionWriter}");
}
public String getFilePath() {
filePath = getDirectory();
return filePath;
}
// Reads the folder to write the log file from web.xml context-param.
// default folder : D://incident
private String getDirectory() {
String directoryName = ContextUtil.getContextProperty(FacesContext.getCurrentInstance(), "incidentFilePath");
File theDir = new File(directoryName);
if(theDir.exists() &&theDir.isDirectory()) {
return directoryName;
}
return "D://incident";
}
public void setExceptionID(String exceptionID) {
this.exceptionID = exceptionID;
}
public String getExceptionID() {
return exceptionID;
}
}
#3. Redirect the user to an static error page :
private void redirectToErrorPage(FacesContext facesContext) throws IOException {
ExternalContext ectx = facesContext.getExternalContext();
ectx.redirect("pages/common/Error.jspx");
}
The Error.jspx:
<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<f:view>
<af:document id="d1">
<af:form id="f1">
<af:panelHeader text="The server is unable to respond at this time. Thank you for your patience." id="ph1">
<af:outputFormatted value="An unexpected error occurred, please contact System Administrator with the following number : #{ExceptionWriter.exceptionID}" id="of2"/>
<!-- PUT a navigation to the HOME page of your application here -->
</af:panelHeader>
</af:form>
</af:document>
</f:view>
</jsp:root>
#4. Results :
can you provide us with the imports , its just not working with any package i've defined
ReplyDeleteHi Ahmed,
DeleteHere is the list of imports for the classes. Hope this helps.
MyExceptionHandler :
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.String.format;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Map;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import oracle.adf.share.ADFContext;
import oracle.adf.view.rich.context.ExceptionHandler;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
ExceptionWriter :
import java.io.File;
import javax.faces.context.FacesContext;
Thanks alot , Soham
Deletewould you please provide the source code, Regards
ReplyDeleteHi, Would you please release the source code, Regards
ReplyDeleteBlog was amazing and worth a while.
ReplyDeleteHow to build chatbots/a>
Hi thanks for sharing thiis
ReplyDelete