Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 223
  • Last Modified:

where to throw and where to catch the Exception in a web application?

Dear experts,

I am writing a web app which mainly used JSP. I just wonder where should we throw the or catch exceptions? Since it is a web app, I don't think it would make much sense to catch the exception before it reaches the browser. I wonder what would be the standard way to handle this? Should we also use "log" to log the error from server side? What is the best way to implement this?

Thanks.
0
changcy77
Asked:
changcy77
  • 6
  • 6
  • 2
  • +2
1 Solution
 
girionisCommented:
 Exceptions to web applications do not differ from exceptions to standard Java applications. You still need to catch a FileNotFoundException for instance if you are doing file processing on the server side. If you do not catch an exception you make the debugging more difficult and the flow of your web app ambiguous.

  As for logging I'd say it depends. If the project is very big then I strongly suggest loging since you can always go through the log files for usefl information. You might also want to take a look at log4j from the apache project: http://jakarta.apache.org/log4j/docs/index.html
0
 
changcy77Author Commented:
Thanks.

Could you please explain a little more about what you meant by "the flow of your web app ambiguous."?

So, should not the user be informed if something goes wrong at the server side?

Thanks.
0
 
amit_chauhanCommented:
You will still catch the exception in jsp the same way as you do in java as girionis mentioned, like this:
<%
  try
  {
    // Some java code here
    ....
  }
  catch (Exception e)
  {
    e.printStackTrace ();
  }
%>

But JSPs has one more directive to handle unhandled exceptions.
On the top, put this in your jsp :

<%@ page errorPage="error.jsp"%>

What does this directory means is that error.jsp is an error page, and any exception occuring on the current jsp which is not handled, will redirect the jsp to error.jsp page where the exception will be available to error.jsp as the variable by the name 'exception'.

So your error.jsp will look something like this :

<%@ page isErrorPage="true" %>
<%@ page import="java.io.*" %>
 Exception Stacktrace:<br>
    <% exception.printStackTrace();

        StringWriter sr = new StringWriter ();
        exception.printStackTrace (new PrintWriter (sr));
        String stkTrace = sr.toString ();
    %>
    <%= SIPSUtils.replace (stkTrace, "\n", "<br>") %>


Hope that helps
Thanks
Amit
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
girionisCommented:
 By saying that you make the flow of your web app ambiguous I mean that you are never sure what the flow is. Imagine if an exception occurs and you do not catch it, you can never be sure if the flow went through the right statement or not.

  Besides as amit_chauhan pointed out JSP pages have the advantage to redirect the error output to another page so the user is informed about the error.

> So, should not the user be informed if something goes wrong at the server side?

  This depends heavily on the kind of exception. If you follow the EJB model you will see that only application level exceptions need to be thrown back to the user. By application level exeptions I mean exceptions that concern the web application and the user (for example you might define your own exception about insufficient funds in a banking web application) needs to know about it. System level exceptions (such as database or network problems) do not usually need to be thrown back to the client, but you could if you wanted.
0
 
changcy77Author Commented:
Thanks to both. It's very helpful.

But, Amit that does this do?
  <%= SIPSUtils.replace (stkTrace, "\n", "<br>") %>
0
 
amit_chauhanCommented:
Oh :) am sorry, I cut-pasted the code from my application, which has a utility method to search and replace a string. You can ignore that. Basically as am displaying this on web page, I have to replace new line characters with <br> tag.
Just print the stacktrace :
Replace that code with this :
<%=stkTrace%>

Thanks
Amit

0
 
objectsCommented:
You should be catching exceptions if you need to perform some action to handle them.
And set up specific error pages in web.xml to handle uncaught exceptions.

0
 
amit_chauhanCommented:
That could be a good idea too if you want to handle specific exceptions differently, or forwarding them to specific pages based on the exception.

But as Objects mentioned, you should be catching exceptions. As a good practice, have your java code in jsp on the top, before html begins, and the code should be within try-catch block to catch all exceptions. You can rethrow the exception after logging it (or performing some action), which will redirect the page to error.jsp page if you have included the errorPage directive. error.jsp chould be primarily used when some unhandled exception occurred while printing html.

Thanks
Amit
0
 
Mayank SAssociate Director - Product EngineeringCommented:
JSP.... ?? I think the errorPage option is the best, as amit_chauhan has already suggested.

Mayank.
0
 
objectsCommented:
> I think the errorPage option is the best

But there are still times where an exception will need to be caught and handled. Just displaying an error page is not always sufficient.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Agreed, buddy.... I think there are enough comments here to help him with that//

Cheers,

Mayank.
0
 
changcy77Author Commented:

From "asker" point of view, comments are always welcomed and never too much. I thank everyone's input.

I will think about it and decide how to give the points.
0
 
changcy77Author Commented:

Dear experts,

This brought up another question...

I also wondering if we are not at the console, but running a remote server, how could the catch exception help us debugging? I mean we can't see the "System.out.println", right? What is the common practice people use for web debugging? Should we write to a file instead?

Thanks.
0
 
amit_chauhanCommented:
Write to a file or send an error email.
Usually you can write to System.err and in most production system this is redirected to a file. check how its organised in your prod system. If its still stdout, then write to a file urself.

Thanks
Amit
0
 
changcy77Author Commented:
Thanks very much, Amit.

I am going to raise the points to 50 since it is getting more challenging...

Another question is then how do you handle different type of exceptions? Does it depend on the business rule?

But, just generally speaking, how does people handle each of these? Is it acceptable to just display an error page to the user or it should always ends with nice messages?

1. If database connection has problem
2. database query return no result
3. database insert failed
4. User input error ( showsing remind meesage to user to ask for correct input)
0
 
amit_chauhanCommented:
Validataion messages, like mandatory fields not entered or invalid values entered should be displayed as is on the page.

For other exceptions, like Database exceptions or unhandled runtime exceptions, it depends from system to system how you want to display it. In some configurations, you just display a nice message, like 'Database error occurred' or 'System error occurred' to the user and log the actual error and exception stacktrace in some log file or error file. But in some other cases, you may want to display the actual error message on the screen to the user. This could be the case, where users usually take the screen shot of the error and send it to the support team. Also its sometimes difficult to search in the log files what was the error, as there could be so many users logged in simulatenously and by the time support team gets the error notification, log file would have advanced a lot and it becomes difficult to locate what caused the error.

You decide how you want it to be.
My suggestion, display the actual error message and give a detail link to display the exception stack trace.

Hope that helps
Thanks
Amit
0
 
changcy77Author Commented:


Thanks.

Another question(sorry) is what option should we choose when we catch exceptions? I have used e.getMessage(), e.toString(), printStackTracke() ...I can't really see the benefit of over the others, any rule for this?
0
 
amit_chauhanCommented:
e.getMessage (), e.toString () and e.printStackTrace () gives error details in increasing order of detail level.

e.getMessage () returns just the error message, like 'File not found at c:\abc\x.txt" etc.

e.toString () returns the message as well as the exception name. e.g java.io.FileNotFoundException : 'File not found at c:\abc\x.txt".

e.printStackTrace () gives the whole exception stacktrace starting from the String returned by toString () method and then the trace from which class/method the error occurred to the one that initiated the call.
e.g.

java.io.FileNotFoundException : 'File not found at c:\abc\x.txt".
at com.abc.xyz.class1.java (line 23)
at com.abc.xyz.class2.java (line 123)
at com.abc.xyz.class3.java (line 43)


Hope that helps
Thanks
Amit
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 6
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now