Exception handling in servlet [duplicate] - java

This question already has answers here:
How to Properly Handle Exceptions in a JSP/Servlet App?
(4 answers)
Closed 6 years ago.
I have JSP with several the fields one of which is Date, server side as servlets.
I have Date check at client side, and i want to make Date check at server side.
I have a method that convert Date from string, which is getted from request.
public static Date convertToDate (String s) throws ParseException {
return formatter.parse(s);
}
I use this method with try/catch
try {
Date date = Utils.convertToDate(request.getParameter("Date")));
} catch (ParseException e) {
//throw what? new Exception or ParseException or something else
throw new ParseException (request.getParameter("Date")+ "is not a Date");
}
Finally, I handle exception at controller servlet like
try {
//some methods that use method convertToDate
} catch (SomeException e) { //required right exception
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
}
Questions. Should I create new ParseException for adding information or create new exception like IncorrectDateException? Are there more suitable options for handling exception?
Thanks.

The standard thing to do is have your Servlet's doXxx() method (eg. doGet(), doPost(), etc.) throw a ServletException and allow the container to catch and handle it. You can specify a custom error page to be shown in WEB-INF/web.xml using the tag:
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
If you end up catching an Exception you can't elegantly handle, just wrap it in a ServletException like this:
try {
// code that throws an Exception
} catch (Exception e) {
throw new ServletException(e);
}

Related

What happens if one filter throws Exceptions in servlet?

I want to add a filter to an existing project, and don't expect my filter to affect the original process in abnormal case. In any cases, the original filter should be executed.
So, I want to know, how should I process when I catch an Exception:
throw the Exception
catch the Exception and call chain.doFilter();
do nothing, like the following code:
if (filter != null) {
filter.doFilter(req,resp,chain);
// should I catch the exception here?
} else {
chain.doFilter(req,resp);
}
Thanks all.
nest your try-catch block inside if(filter!=null)
For instance:
if(filter != null){
try{} catch (Exception e){
//do something
}
}
Also you can use finally after catch for any clean up or code you want to run no whether an exception is caught or not.

Exceptions not showing up in console unless explicitly caught

I'm using SparkJava and it seems that exceptions thrown in routes are not showing up in console unless I explicitly catch them.
For example, given
Spark.post("/lookup", this::lookup);
and
private String lookup(Request req, Response res) {
// some stuff
return json.toString();
}
If // some stuff throws an exception, nothing appears in console. But if I explicitly catch and print the exception, it prints it to console as expected.
private String lookup(Request req, Response res) {
try {
// some stuff
} catch(Exception e) {e.printStackTrace();}
return json.toString();
}
This leads me to believe that somewhere further up in the route callstack, all exceptions are caught and hidden.
As you can imagine, this behavior results in some rather frustrating debugging. Is there any way to make it so that all exceptions are always shown in console?
In your Main class, before any routes, add this:
exception(Exception.class, (exception, request, response) -> {
exception.printStackTrace();
});
Any exception not otherwise caught by your application code will now be dumped to the console.
(IMO Spark should do this by default...)

ClassCastException in spring

I am trying to catch an exception and return a value to my client page, but I get ClassCastException and it is not returning any value.
My code snippet-
#RequestMapping(value = "/config/MyFile/data", method = RequestMethod.GET)
#ResponseBody
public List<Myfile> getAllFlatFileTrafficCops()
{
try
{
return MyFileServices.getAlldata();
}
catch (final ResourceAccessException r)
{
final Throwable flatfileTrafficCopStatus;
flatfileTrafficCopStatus = r.getCause();
return (List<FlatFileTrafficCop>) flatfileTrafficCopStatus;
}
}
All you can do in this case in Exception situation catch the exception and encapsulate it in your meaningful custom exception and propagate it back to caller function and for web display meaningful error text.
Always propagate exceptions back to caller. For debug you might want to add a log statement over there.
catch (final ResourceAccessException r)
{
CustomException cException = new CustomException(r);
throw cException;
//OR
FlatFileTrafficCop emptyObj= new FlatFileTrafficCop(Witherr);
//add that in a list and return
}
first is ClassCastException child of ResourceAccessException? No, so your catch will not work, if you want to catch ClassCastException you have to make 2nd catch for it
catch (final ClassCastException e){}
but while you are using spring no need to catch it like this you can use #ExceptionHandler instead

How to retrieve error message in StringTemplate?

How can I retrieve a compile time error message from StringTemplate as a String?
This code for instance:
STGroup stg = new STGroup('<', '>');
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
if (compiledTemplate == null)
System.out.println("Template is invalid");
Will simply log something like "invalid came as a complete surprise to me", but I want to display this error message in my UI.
I can access the ErrorManager with stg.errMgr. I expected a method like getErrors() here, but there isn't...
You could set an error listener for the group, which would allow you to catch the error, and then pass it to the UI from there.
This answer tells you more about implementing an STErrorListener. The example they give doesn't compile since they're throwing checked exceptions from within the ErrorListener. Perhaps a better approach would be to handle the errors directly inside the listener, or you could just throw a RuntimeException so you could catch the errors when you call stg.defineTemplate(...).
public class MySTErrorListener implements STErrorListener {
...
#Override
public void compileTimeError(STMessage msg) {
// do something useful here, or throw new RuntimeException(msg.toString())
}
...
}
If you were to throw the RuntimeException you could then catch it when you define the ST:
stg.setListener(new MySTErrorListener());
try{
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
} catch (Exception e)
{
// tell the UI about the error
}

Using the content handler API (JSR 211) to open applications

I want to be able to launch native and J2ME applications through my application using the content handler API (JSR 211) on a Nokia 6212.
At the moment, I am unable to do so, as it always states that there is "No Content Handler Found" and throws a javax.microedition.content.ContentHandlerException.
At the moment, I am trying to get the phone to launch its browser and go to a certain website, just to test that I can use the framework. I have tried many different Invocation objects:
//throw exceptions
new Invocation("http://www.somesite.com/index.html",
"application/internet-shortcut");
new Invocation("http://www.google.co.uk","text/html");
// a long shot, I know
new Invocation("http://www.somesite.com/text.txt","text/plain");
// massive long shot
new Invocation("http://www.google.co.uk","application/browser");
//appears to download the link and content (and definitely does in the Nokia
// emulator) and then throws an exception
new Invocation("http://www.google.co.uk");
new Invocation("http://www.somesite.com/index.html");
Below is the code that I have been using, please bear in mind the parameters often changed to generate the different Invocation objects.
/*
* Invokes an application using the Content Handler API
*/
public void doInvoke(String url, String mime, String payload){
Registry register = Registry.getRegistry(this.getClass().getName());
Invocation invoke = new Invocation(url, mime, null, false,
ContentHandler.ACTION_OPEN);
boolean mustQuit = false;
try {
mustQuit = register.invoke(invoke);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ContentHandlerException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(mustQuit){
this.quit();
}
}
Try this:
Registry register = Registry.getRegistry(this.getClass().getName());
You must call Registry.getRegistry for the MIDlet inheritor. Just use your MIDlet for getting the class name.

Categories