ClassCastException in spring - java

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

Related

Java JSON unit test pass with wrong value

I have the following function:
public class NorthboundApiLogicTest {
#Test
public void testIfParametersValuesAreCorrect() {
String body = "{\"exception\":\"world\",\"error\":\"Not Found\",\"message\":\"hello\""
+ ",\"timestamp\":\"2020-01-07T12:26:48.334386Z\",\"status\":\"404\"}";
try {
JSONAssert.assertEquals("{message:hello, exception:world, status:403, error:Not Found}",
body, false);
} catch (Exception e) {
System.err.println(e);
}
System.out.println(body);
}
}
I run this test with Maven, and strangely it pass successfully.
However, it should not, because I assert that status=403 but the value is 404. What am I doing wrong?
It's failing to parse the JSON before it even performs an assertion on the structure, and you're simply logging that via your catch.
catch (Exception e) {
System.err.println(e);
}
You need to let that exception be thrown from the method, or catch it and call fail() with an appropriate message.
And then fix the issue of your non-parseable JSON, of course!

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...)

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
}

Exception handling in servlet [duplicate]

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);
}

Categories