SlideShare a Scribd company logo
EXCEPTION
HANDLING
&
LOGGING
BEST PRACTICES
Angelin
AGENDA
Logging using Log4j

“Logging” Best Practices
“Exception Handling” Best Practices
CodePro Errors and Fixes
Logging using Log4j
Logging using Log4j
Log4j - logging library for Java

Logging Levels (in lowest to highest order)
The standard levels of Log4j are ordered as
ALL < TRACE < DEBUG < INFO < WARN < ERROR <
FATAL < OFF
Logging using Log4j
Level

Description

ALL

The lowest possible rank and is intended to turn on all levels of
logging including custom levels.

TRACE

Introduced in log4j version 1.2.12, this level gives more detailed
information than the DEBUG level.

DEBUG

Designates fine-grained informational messages that are most
useful to debug an application.

INFO

Designates informational messages that highlight the progress of
the application at coarse-grained level.

WARN

Designates potentially harmful situations. This level can be used
to warn usage of deprecated APIs, poor use of API, ‘almost’
errors and other runtime situations that are undesirable or
unexpected, but not necessarily “wrong”.
Logging using Log4j
Level

Description

ERROR

Designates error events that might still allow the application to
continue running. This level can be used to inform about a
serious error which needs to be addressed and may result in
unstable state.

FATAL

Designates very severe error events that will presumably lead
the application to abort.

OFF

The highest possible rank and is intended to turn off logging.
How Logging Level works?
A logging request of a particular level is said to be enabled if that
level is higher than or equal to the level of its logger.
Example
import org.apache.log4j.*;
public class LogClass {
private static final org.apache.log4j.Logger LOGGER =
Logger.getLogger(LogClass.class);
public static void main(String[] args) {
LOGGER.setLevel(Level.WARN);
LOGGER.trace("Trace Message!");
LOGGER.debug("Debug Message!");
LOGGER.info("Info Message!");
LOGGER.warn("Warn Message!");
LOGGER.error("Error Message!");
LOGGER.fatal("Fatal Message!");
}
}

Output:
Warn Message!
Error Message!
Fatal Message!
“Logging”
BEST PRACTICES
Logging - Best Practices
Declare the logger to be both static and final to ensure
that every instance of a class shares the common logger
object.

Add code to check whether logging has been enabled at
the right level.
Use meaningful log messages that are relevant to the
context.
Logging - Best Practices
Better to use logging only to log the following,

method entry (optionally with the method’s input
parameter values)
method exit
root cause message of exceptions that are handled at
the exception’s origin point.
Logging - Best Practices
 Any other intermediate redundant logging statements, which
are used just for the purpose of debugging can still be
avoided.
Example
try {
LOGGER.debug(“About to enter getSkuDescription method”);
// The above logging statement is not required,
// if getSkuDescription() method logs its method entry
String skuDesc = getSkuDescription(skuNumber);
LOGGER.debug(“Exited getSkuDescription method”);
// The above logging statement is not required,
// if getSkuDescription() method logs its method exit
} catch (ServiceException se) {
LOGGER.error(se.getErrorMessage());
throw se;
}
Logging - Best Practices
Avoid logging at ‘every’ place where a custom exception is
thrown and instead log the custom exceptions’ message
in its ‘catch’ handler.
Example
try {
if (null == skuNumber || skuNumber.isEmpty()) {
LOGGER.error(“Sku number is invalid”);
// The above logging statement is not required,
// since the catch handler logs the message
throw new ServiceException(“Sku number is invalid”);
}
Logging - Best Practices
try {

sku = Integer.parseInt(skuNumber);
} catch (NumberFormatException nfe) {
LOGGER.error(“Sku number is invalid and not a number”);
// The above logging statement is not required,
// since the catch handler logs the message
throw new ServiceException(“Sku number is invalid and
not a number”, nfe);
}
……
} catch (ServiceException se) {
LOGGER.error(se.getErrorMessage());
throw se;
}
Exception handling
Best Practices
Exception Handling - Best Practice #1
Handle Exceptions close to its origin
 Does NOT mean “catch and swallow” (i.e. suppress or ignore
exceptions)
try {
// code that is capable of throwing a XyzException
} catch ( XyzException e) {
// do nothing or simply log and proceed
}
 It means, “log and throw an exception relevant to that source
layer”
– DAO layer - DataAccessException
– Business layer - ApplicationException (example OUSException)
Exception Handling - Best Practice #1
Important Note
In applications using Web Services, the Web Service (a.k.a
Resource) layer,
 should catch ALL exceptions and handle them by creating proper

error response and send it back to client.
 should NOT allow any exception (checked or unchecked) to be
“thrown” to client.
 should handle the Business layer exception and all other
unchecked exceptions separately.
Exception Handling - Best Practice #1
Example
try {
// code that is capable of throwing an ApplicationException
} catch (ApplicationException e) {
// form error response using the exception’s
// data – error code and/or error message
} catch (Exception e) {
// log the exception related message here, since this block is
// expected to get only the unchecked exceptions
// that had not been captured and logged elsewhere in the code.
// form error response using the exception’s
// data – error code and/or error message
}
The catch handler for ‘Exception’ in the Web Service layer is expected to
handle all unchecked exceptions thrown from within ‘try’ block
Exception Handling - Best Practice #2
Log Exceptions just once and log it close to its origin
Logging the same exception stack trace more than once can confuse
the programmer examining the stack trace about the original source
of exception.
try {
// code that is capable of throwing a XyzException
} catch (XyzException e) {
// log the exception specific information
// throw exception relevant to that source layer
}
Exception Handling - Best Practice #2
#1 - When catching an exception and throwing it through an
exception relevant to that source layer, make sure to use the
construct that passes the original exception’s cause. Otherwise,
CodePro will report "No cause specified when creating exception“.
try {
// code that is capable of throwing a SQLException
} catch (SQLException e) {
// log technical SQL Error messages, but do not pass
// it to the client. Use user-friendly message instead
LOGGER.error(“An error occurred when searching for the SKU
details” + e.getMessage());
throw new DataAccessException(“An error occurred when
searching for the SKU details”, e);
}
Exception Handling - Best Practice #2
#2 - There is an exception to this rule, in case of existing code that
may not have logged the exception details at its origin. In such
cases, it would be required to log the exception details in the first
method up the call stack that handles that exception. But care
should be taken not to COMPLETELY overwrite the original
exception’s message with some other message when logging.
Example
DAO Layer:
try {
// code that is capable of throwing a SQLException
} catch (SQLException e) {
// LOGGING missed here
throw new DataAccessException(“An error occurred
when processing the query.”, e);
}
Exception Handling - Best Practice #2
Processor Layer:
try {
// code that is capable of throwing a DataAccessException
} catch (DataAccessException e) {
// logging is mandated here as it was not logged
// at its source (DAO layer method)
LOGGER.error(e.getMessage());
throw new OUSException(e.getMessage(), e);
}
Exception Handling - Best Practice #3
Do not catch “Exception”
Accidentally swallowing RuntimeException
try {
doSomething();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
This code
1. also captures any RuntimeExceptions that might have been
thrown by doSomething,
2. ignores unchecked exceptions and
3. prevents them from being propagated.
Exception Handling - Best Practice #3
Important Note (about some common RuntimeExceptions)
NullPointerException – It is the developer’s responsibility to
ensure that no code can throw it. Run CodePro and add null
reference checks wherever it has been missed.

NumberFormatException, ParseException – Catch these and
create new exceptions specific to the layer from which it is thrown
(usually from business layer) using user-friendly and non technical
messages.
Exception Handling - Best Practice #3
Important Note (about some common RuntimeExceptions)
Example
try {
int sku = Integer.parseInt(skuNumber);
} catch (NumberFormatException nfe) {
LOGGER.error("SKU number is invalid and not a number");
throw new OUSException("SKU number is invalid and not a
number", nfe);
}
All other unchecked exceptions (RuntimeExceptions) will be
caught and handled by the Web Service layer (as explained in Best
Practice #1).
CODEPRO
Errors & fixes
Fix to common CodePro errors
"Invalid exception parameter name"
Solution
Rename the parameter to “e”
Example
try {
// code that is capable of throwing a DataAccessException
} catch (DataAccessException e) {
throw new OUSException(e.getMessage(), e);
}
Fix to common CodePro errors
"No cause specified when creating exception" when wrapping
an exception into another exception.
Solution
Use the construct that passes the original exception’s cause
Example
try {
// code that is capable of throwing a SQLException
} catch (SQLException e) {
LOGGER.error(e.getMessage());
throw new DataAccessException(“An error occurred
when searching for the SKU details”, e);
}
THANK YOU

More Related Content

What's hot

concurrency-control
concurrency-controlconcurrency-control
concurrency-control
Saranya Natarajan
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Java rmi
Java rmiJava rmi
Java rmi
kamal kotecha
 
Access Protection
Access ProtectionAccess Protection
Access Protectionmyrajendra
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
Questpond
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
Venkata Sreeram
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Message and Stream Oriented Communication
Message and Stream Oriented CommunicationMessage and Stream Oriented Communication
Message and Stream Oriented Communication
Dilum Bandara
 

What's hot (20)

concurrency-control
concurrency-controlconcurrency-control
concurrency-control
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
interface in c#
interface in c#interface in c#
interface in c#
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java rmi
Java rmiJava rmi
Java rmi
 
Access Protection
Access ProtectionAccess Protection
Access Protection
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
Generics
GenericsGenerics
Generics
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Message and Stream Oriented Communication
Message and Stream Oriented CommunicationMessage and Stream Oriented Communication
Message and Stream Oriented Communication
 

Similar to Exception handling and logging best practices

ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
Randy Connolly
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
Riccardo Cardin
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application Development
Ketan Raval
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java ProblemsEberhard Wolff
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Exceptions
ExceptionsExceptions
Exceptions
DeepikaT13
 
Error management
Error managementError management
Error managementdaniil3
 

Similar to Exception handling and logging best practices (20)

ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application Development
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exceptions
ExceptionsExceptions
Exceptions
 
Error management
Error managementError management
Error management
 

More from Angelin R

Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
Angelin R
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube
Angelin R
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
Angelin R
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
Angelin R
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of Me
Angelin R
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential Traits
Angelin R
 
Action Script
Action ScriptAction Script
Action Script
Angelin R
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM MethodologyAngelin R
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship SongsAngelin R
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML Programming
Angelin R
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe Flex
Angelin R
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)
Angelin R
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
Angelin R
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work Model
Angelin R
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building Activities
Angelin R
 
XStream
XStreamXStream
XStream
Angelin R
 

More from Angelin R (16)

Comparison of Java Web Application Frameworks
Comparison of Java Web Application FrameworksComparison of Java Web Application Frameworks
Comparison of Java Web Application Frameworks
 
[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube[DOC] Java - Code Analysis using SonarQube
[DOC] Java - Code Analysis using SonarQube
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
 
The principles of good programming
The principles of good programmingThe principles of good programming
The principles of good programming
 
A Slice of Me
A Slice of MeA Slice of Me
A Slice of Me
 
Team Leader - 30 Essential Traits
Team Leader - 30 Essential TraitsTeam Leader - 30 Essential Traits
Team Leader - 30 Essential Traits
 
Action Script
Action ScriptAction Script
Action Script
 
Agile SCRUM Methodology
Agile SCRUM MethodologyAgile SCRUM Methodology
Agile SCRUM Methodology
 
Tamil Christian Worship Songs
Tamil Christian Worship SongsTamil Christian Worship Songs
Tamil Christian Worship Songs
 
Flex MXML Programming
Flex MXML ProgrammingFlex MXML Programming
Flex MXML Programming
 
Introduction to Adobe Flex
Introduction to Adobe FlexIntroduction to Adobe Flex
Introduction to Adobe Flex
 
Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)Software Development Life Cycle (SDLC)
Software Development Life Cycle (SDLC)
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 
Effective Team Work Model
Effective Team Work ModelEffective Team Work Model
Effective Team Work Model
 
Team Building Activities
Team Building ActivitiesTeam Building Activities
Team Building Activities
 
XStream
XStreamXStream
XStream
 

Recently uploaded

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 

Exception handling and logging best practices

  • 2. AGENDA Logging using Log4j “Logging” Best Practices “Exception Handling” Best Practices CodePro Errors and Fixes
  • 4. Logging using Log4j Log4j - logging library for Java Logging Levels (in lowest to highest order) The standard levels of Log4j are ordered as ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
  • 5. Logging using Log4j Level Description ALL The lowest possible rank and is intended to turn on all levels of logging including custom levels. TRACE Introduced in log4j version 1.2.12, this level gives more detailed information than the DEBUG level. DEBUG Designates fine-grained informational messages that are most useful to debug an application. INFO Designates informational messages that highlight the progress of the application at coarse-grained level. WARN Designates potentially harmful situations. This level can be used to warn usage of deprecated APIs, poor use of API, ‘almost’ errors and other runtime situations that are undesirable or unexpected, but not necessarily “wrong”.
  • 6. Logging using Log4j Level Description ERROR Designates error events that might still allow the application to continue running. This level can be used to inform about a serious error which needs to be addressed and may result in unstable state. FATAL Designates very severe error events that will presumably lead the application to abort. OFF The highest possible rank and is intended to turn off logging.
  • 7. How Logging Level works? A logging request of a particular level is said to be enabled if that level is higher than or equal to the level of its logger. Example import org.apache.log4j.*; public class LogClass { private static final org.apache.log4j.Logger LOGGER = Logger.getLogger(LogClass.class); public static void main(String[] args) { LOGGER.setLevel(Level.WARN); LOGGER.trace("Trace Message!"); LOGGER.debug("Debug Message!"); LOGGER.info("Info Message!"); LOGGER.warn("Warn Message!"); LOGGER.error("Error Message!"); LOGGER.fatal("Fatal Message!"); } } Output: Warn Message! Error Message! Fatal Message!
  • 9. Logging - Best Practices Declare the logger to be both static and final to ensure that every instance of a class shares the common logger object. Add code to check whether logging has been enabled at the right level. Use meaningful log messages that are relevant to the context.
  • 10. Logging - Best Practices Better to use logging only to log the following, method entry (optionally with the method’s input parameter values) method exit root cause message of exceptions that are handled at the exception’s origin point.
  • 11. Logging - Best Practices  Any other intermediate redundant logging statements, which are used just for the purpose of debugging can still be avoided. Example try { LOGGER.debug(“About to enter getSkuDescription method”); // The above logging statement is not required, // if getSkuDescription() method logs its method entry String skuDesc = getSkuDescription(skuNumber); LOGGER.debug(“Exited getSkuDescription method”); // The above logging statement is not required, // if getSkuDescription() method logs its method exit } catch (ServiceException se) { LOGGER.error(se.getErrorMessage()); throw se; }
  • 12. Logging - Best Practices Avoid logging at ‘every’ place where a custom exception is thrown and instead log the custom exceptions’ message in its ‘catch’ handler. Example try { if (null == skuNumber || skuNumber.isEmpty()) { LOGGER.error(“Sku number is invalid”); // The above logging statement is not required, // since the catch handler logs the message throw new ServiceException(“Sku number is invalid”); }
  • 13. Logging - Best Practices try { sku = Integer.parseInt(skuNumber); } catch (NumberFormatException nfe) { LOGGER.error(“Sku number is invalid and not a number”); // The above logging statement is not required, // since the catch handler logs the message throw new ServiceException(“Sku number is invalid and not a number”, nfe); } …… } catch (ServiceException se) { LOGGER.error(se.getErrorMessage()); throw se; }
  • 15. Exception Handling - Best Practice #1 Handle Exceptions close to its origin  Does NOT mean “catch and swallow” (i.e. suppress or ignore exceptions) try { // code that is capable of throwing a XyzException } catch ( XyzException e) { // do nothing or simply log and proceed }  It means, “log and throw an exception relevant to that source layer” – DAO layer - DataAccessException – Business layer - ApplicationException (example OUSException)
  • 16. Exception Handling - Best Practice #1 Important Note In applications using Web Services, the Web Service (a.k.a Resource) layer,  should catch ALL exceptions and handle them by creating proper error response and send it back to client.  should NOT allow any exception (checked or unchecked) to be “thrown” to client.  should handle the Business layer exception and all other unchecked exceptions separately.
  • 17. Exception Handling - Best Practice #1 Example try { // code that is capable of throwing an ApplicationException } catch (ApplicationException e) { // form error response using the exception’s // data – error code and/or error message } catch (Exception e) { // log the exception related message here, since this block is // expected to get only the unchecked exceptions // that had not been captured and logged elsewhere in the code. // form error response using the exception’s // data – error code and/or error message } The catch handler for ‘Exception’ in the Web Service layer is expected to handle all unchecked exceptions thrown from within ‘try’ block
  • 18. Exception Handling - Best Practice #2 Log Exceptions just once and log it close to its origin Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. try { // code that is capable of throwing a XyzException } catch (XyzException e) { // log the exception specific information // throw exception relevant to that source layer }
  • 19. Exception Handling - Best Practice #2 #1 - When catching an exception and throwing it through an exception relevant to that source layer, make sure to use the construct that passes the original exception’s cause. Otherwise, CodePro will report "No cause specified when creating exception“. try { // code that is capable of throwing a SQLException } catch (SQLException e) { // log technical SQL Error messages, but do not pass // it to the client. Use user-friendly message instead LOGGER.error(“An error occurred when searching for the SKU details” + e.getMessage()); throw new DataAccessException(“An error occurred when searching for the SKU details”, e); }
  • 20. Exception Handling - Best Practice #2 #2 - There is an exception to this rule, in case of existing code that may not have logged the exception details at its origin. In such cases, it would be required to log the exception details in the first method up the call stack that handles that exception. But care should be taken not to COMPLETELY overwrite the original exception’s message with some other message when logging. Example DAO Layer: try { // code that is capable of throwing a SQLException } catch (SQLException e) { // LOGGING missed here throw new DataAccessException(“An error occurred when processing the query.”, e); }
  • 21. Exception Handling - Best Practice #2 Processor Layer: try { // code that is capable of throwing a DataAccessException } catch (DataAccessException e) { // logging is mandated here as it was not logged // at its source (DAO layer method) LOGGER.error(e.getMessage()); throw new OUSException(e.getMessage(), e); }
  • 22. Exception Handling - Best Practice #3 Do not catch “Exception” Accidentally swallowing RuntimeException try { doSomething(); } catch (Exception e) { LOGGER.error(e.getMessage()); } This code 1. also captures any RuntimeExceptions that might have been thrown by doSomething, 2. ignores unchecked exceptions and 3. prevents them from being propagated.
  • 23. Exception Handling - Best Practice #3 Important Note (about some common RuntimeExceptions) NullPointerException – It is the developer’s responsibility to ensure that no code can throw it. Run CodePro and add null reference checks wherever it has been missed. NumberFormatException, ParseException – Catch these and create new exceptions specific to the layer from which it is thrown (usually from business layer) using user-friendly and non technical messages.
  • 24. Exception Handling - Best Practice #3 Important Note (about some common RuntimeExceptions) Example try { int sku = Integer.parseInt(skuNumber); } catch (NumberFormatException nfe) { LOGGER.error("SKU number is invalid and not a number"); throw new OUSException("SKU number is invalid and not a number", nfe); } All other unchecked exceptions (RuntimeExceptions) will be caught and handled by the Web Service layer (as explained in Best Practice #1).
  • 26. Fix to common CodePro errors "Invalid exception parameter name" Solution Rename the parameter to “e” Example try { // code that is capable of throwing a DataAccessException } catch (DataAccessException e) { throw new OUSException(e.getMessage(), e); }
  • 27. Fix to common CodePro errors "No cause specified when creating exception" when wrapping an exception into another exception. Solution Use the construct that passes the original exception’s cause Example try { // code that is capable of throwing a SQLException } catch (SQLException e) { LOGGER.error(e.getMessage()); throw new DataAccessException(“An error occurred when searching for the SKU details”, e); }