Where to catch exceptions in a MVC framework - java

Everyone talks about how important exception handling is. I have never had the need to handle them until recently:
try {
$pdo = new PDO($dns);
} catch (Exception $e) {
throw new Exception($e);
}
Another more general example would be:
if ($something) {
throw new Exception('Ouch! I can't do that!');
}
After a little online research, I found that many examples/solutions online simply echo them. (PDO Exception Questions - How to Catch Them) Some don't have solutions. (Catching PDOException in lower layer and re-throwing as different exception to upper layer) & (Where to catch exception in PHP MVC application?) And others, I just dont understand. (Where to catch exceptions)
Question #1: Where should I catch exceptions; in the Model or Controller of a MVCish framework?
Question #2: What should catching it do? Log it, email it, display 503?

I am a .net guy and for me best practices for catching exceptions:
Catch it as late as possible.
Write a common code to catch exception.
Catch it at controller level and log it somewhere with complete stack trace (ETW, Log file, DB etc.).
Redirect user to some good looking error page. Only controller can do this.

Related

Am I abusing the idea of log levels here?

I have a case where I want to introduce some error logging. But at this point I'm not sure how often exceptions will occur here (experimental feature, errors dependent on user input) and I'm a bit worried about flooding the logs with stacktraces.
So I came up with this solution:
catch (Exception ex) {
if (LOGGER.isDebugEnabled()) {
LOGGER.error("Exception during save()", ex); // log with stacktrace
} else {
LOGGER.error("Exception during save(): {}", ex.toString());
}
}
But I'm not really satisfied with this because I feel like abusing the debug level for logging on error level. I use org.slf4j.Logger.
If you're only concerned about not spamming the logs with irrelevant stacktraces, you can still kind of not abuse the idea of log levels but embrace it instead :
catch (Exception ex) {
LOGGER.error("Exception during save(): {}", ex.toString());
LOGGER.debug("Detailed exception output:", ex);
}
Performance-wise your proposed solution using isDebugEnabled scores a little bit better, as the String object (first argument) won't get created for the second call unless you really need it. And you also spare a single level on the call stack.

Why does squid:S1166 not accept exception messages only when logging caught exceptions?

Quote from the description of the rule (SonarQube 4.5.5):
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ }
catch (Exception e) { LOGGER.info(e.getMessage()); }
By providing the exception class to the logger a stack trace is written to the logs.
The problem in our code base is this:
By following the Tell, don't ask principle, we use checked exceptions as part of the, what we consider, normal execution paths and we don't want them to result in unreasonably large log messages.
A few examples: Servers responding with error codes, database statement executions failing on optimistic locking (concurrent users)...
My suggestion: Split this case in two.
// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ }
catch (Exception e) { LOGGER.info(e.getMessage()); }
and
// Compliant - exception is lost (only message is preserved) but there is business logic handling the situation
try {
/* ... */
} catch (Exception e) {
LOGGER.info(e.getMessage());
*/ exception handling */
}
The rule squid:S00108 (code blocks must not be empty) would not catch the problem since there is a logging statement.
Is this not reasonable? Have I missed something of importance?
Note: I've rewritten the question to clarify my use case
I understand the arguments for maintaining the stack trace and all that, but I think it's going to bloat your logs for a < ERROR level event. One solution is to log the message as a WARN and log the exception object as DEBUG or TRACE. That way a normal user log config would not be flooded with business as usual stack traces, but it would still be possible to get a stack trace if necessary.
If it's causing hundreds of what you consider to be FP's then you should think about turning the rule off, or excluding it from your project files.
But to answer your question:
The point of exception logging is to leave enough information for investigators to figure out the cause of a problem.
If your messages are detailed, e.g.
The x in the y method broke because the frabjous was not day enough
then perhaps they fulfill that purpose. But what about a message like
Something went wrong
?
Further, you know exactly what each exception message means, but someday you'll presumably move on to bigger and better things. Will the next guy who supports the system have the same depth of knowledge? He may be grateful for the stacktraces and line numbers that tell him where to start looking...
But finally, I have to ask: why are you getting and logging so many exceptions that you flood the logger?
(Adding another answer to address the question as rewritten:)
Why would you both handle the exception and log it? If it's handled, there's no reason to log.
try to pass whole object to method than just a e.getMessage()LOGGER.info("INFO "e.);

Not able to catch custom exception of web service in their own catch blocks

We are using a web service which throws 3 types of custom web service faults i.e. ServiceException, ConnectionException and InvalidDataException.
Along with these catch blocks, we have also put in the catch block for RemoteAccessException which is the spring's runtime exception.
catch (org.springframework.remoting.RemoteAccessException remoteAccessExc) {
}
While testing the above listed custom exceptions, we found that all these 3 types of exceptions are not getting catched in their respective catch blocks. Instead all gets catched in the last catch block which is the RemoteAccessException. We found during debugging the exception object of soap fault which is of type org.springframework.remoting.jaxws.JaxWsSoapFaultException that the service is throwing the correct faults.
My concern is why these faults are not falling into their own catch blocks. The service itself tells us to handle these exceptions while placing the service call.
When I hit the service through proxy java client, the faults fall correctly into their respective blocks. If there would have been a problem with POJO's then they shouldn't have worked in this case also. But they are working in this case(when hit through java proxy client) which means no problem in POJOs.
We are using spring-2.5.6.jar.
Since you are keeping different catch blocks and the fault object is getting overridden, do the following:
Check whether the fault object is null or not in each catch block, so that when the fault is thrown, it won't get overridden in any other catch block. This is because you put the not null check at every entry of catch block.
try{
//////
}Catch(IllegalArgumentException e){
create fault object;
throw fault;
}
Catch(Exception e){
///check whether fault object is not null
if(fault!=null){
throw fault;
}else{
///another fault object
throw fault1;
}

What to include in the catch clause of Exception

I have a code that throws a bunch of Exceptions but each of them only contains a printStackTrace() method as shown below
} catch (SecurityException e) {
// TODO Auto-generated catch block
System.err.println(e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is this sufficient or do I need to include additional statements like System.err.println(e)? Usually, if an exception occurs I am able to trace the source with the above alone.
If there is something you can do to solve the problem, do it in the catch, if there is nothing you can do, then it is better to use a logging framework to register the exception than to use e.printStackTrace(); or System.err.println(e);
I personally recommend: http://www.slf4j.org/, but if you have masochistic tendencies you can try the very bad (but official) Java Logging API: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/ .
One extra advantage of SLF4J is that it can redirect its logging to the awful Java Logging API (that way you can use an elegantly designed API and still comform to the awfully designed (de jure not de facto) "standard"
SLF4J is easy to use, to log an exception all you have to do is write logger.error("some accompanying message", exception);, another of its advantages is that you can, for example, configure it to send you an email each time your application crashes (by using logback as the underlying logging engine)
It depends on the exceptions. Obviously, with printStackTrace() the exception will be printed for you to debug (or users to report to you). However there is no additional error handling.
Example:
If an IOException is thrown, you might want to show the user a error message specifying the exact error cause, or you might want to do another attempt, transparent for the user. Or you might want to abort the whole program if the operation is critical for the success of the whole task... etc.
If you want to trace the source e.printStackTrace() is enough.
Usually I put e.printStackTrace(); at DEBUG level. Also I add meaningful error message at ERROR level for the users.
I think you might be missing a bit about the basics of exceptions and exception handling.
The golden rule of exceptions is that they should be exceptional.
This is why you might have seen or read that you should never catch the base Exception - there is simply no way that your code can handle every time of exception.
So as a general rule you should only catch exceptions if you can handle them in a specific way. For example, if you're reading a user's details from a file and that fails you might choose to return a new user. What you don't want to do is simply catch the exception and log it. This leads to an application that is robust but simply swallows errors which leads to an extremely bad user experience.
If your method can't handle an exception it should simply not catch it and defer the exception handling to a higher level. This usually means an error message will be displayed to the user (at the top level).
If you can afford to use a logging framework like log4j, you'll be able to call
}catch(Exception e){ log.error("Exception occurred:",e}
making the log framework to log your custom message "Exception occurred" followed by the stack trace in your errorlog file

Is it a bad idea to use printStackTrace() for caugt Exceptions?

Is it a bad idea to use printStackTrace() in Android Exceptions like this?
} catch (Exception e) {
e.printStackTrace();
}
I believe this is what you need:
catch (Exception e) {
Log.e(TAG,Log.getStackTraceString(e));
}
Yes, it is a bad idea. You should instead use Android's built-in log class specifically designed for these purposes: http://developer.android.com/reference/android/util/Log.html
It gives you options to log debug messages, warnings, errors etc.
Logging errors with:
Log.e(TAG, "message", e) where the message can be an explanation of what was being attempted when the exception was thrown
or simply Log.e(TAG, e) if you do not wish to provide any message for context
You can then click on the log console at the bottom while running your code and easily search it using the TAG or log message type as a filter
Yes. printStackTrace() is convenient but discouraged, especially on Android where it is visible through logcat but gets logged at an unspecified level and without a proper message. Instead, the proper way to log an exception is...
Log.e(TAG, "Explanation of what was being attempted", e);
Note that the exception is used as a third parameter, not appended to the message parameter. Log handles the details for you – printing your message (which gives the context of what you were trying to do in your code) and the Exception's message, as well as its stack trace.
The question is: is useful at all print to the stack trace in an Andriod application context?
Will the standard output be visible at runtime? Will somebody care about it?
My point is that, if nobody is going to check the standard output and care to debug the error, the call to this method is dead code, and composing the stacktrace message is a worthless expense. If you need it only for debugging at development, you could set an accesible global constant, and check it at runtime:
} catch (Exception e) {
if(com.foo.MyEnvironmentConstants.isDebugging()) {
e.printStackTrace();
} //else do noting
}
I would avoid using printStackTrace(), use a logging system and its support of exceptions.
log.log(Level.SEVERE, "Uncaught exception", e);
So if you want to change how logging is handled it's much easier.

Categories

Resources