SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Exception handling
Ania Pietras
Exception Handling - general rules
- use exception only for exceptional situation. Creating an exception in Java is expensive and hence you should
not do it just for testing if something is present, valid or permitted. In the latter case design your API to return this
as a regular result.
- every exception has to be logged in specific file to provide necessary information for “service desk”
- decide what is the type of exception:
- Business Exception - caused by invalid behavior of user, which need to be shown to him with specific
message.
- Technical Exception - caused by unexpected and exotic situation, are unchecked and try-catch is needed!
This exception should be wrapped into Business Exception (Runtime exception), which could be shown
to user as “system occur some technical problem, please try later”.
Exception Handling - general rules
- all exceptions should be named in specific and easy to understand way describe what unusual situation
happened. Name suffix should be Exception. Examples: ObjectNotFoundException,
IllegalArgumentException, MissingMetricException, DataValidationException …
- Runtime exceptions have to be represented by specific status - proper for each situation.
Exception Handling - http status
● 304 Not Modified - Used when HTTP caching headers are in play
● 400 Bad Request - The request is malformed, such as if the body does not parse
● 401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup
if the API is used from a browser
● 403 Forbidden - When authentication succeeded but authenticated user doesn't have access to the resource
● 404 Not Found - When a non-existent resource is requested
● 405 Method Not Allowed - When an HTTP method is being requested that isn't allowed for the authenticated
user
● 500 Internal Server Error - when server has internal error, usually some technical or configuration problem
● … more if necessary
global exception
handler/controller layer
service layer
Exception workflow
create exception create bundles
throw & catch Technical
Exception
throw Business
Exception
handle Business
Exception
REST API
Return response with
proper HTTP status and
message
Client
Show view with proper
message
log
log
User
Configurations & examples
Create proper language versions.
//exception.properties
exception.objectNotFound= Cannot find object of type {0}
//exception_pl.properties
exception.objectNotFound= Nie znaleziono obiektu typu {0}
http://www.mkyong.com/spring/spring-resource-bundle-with-resourcebundlemessagesource-example/
Register bundles as @Bean
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new
ReloadableResourceBundleMessageSource();
messageSource.setBasename("/exception");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
Note the basename is filepath of base msg file without .properties extension
http://www.concretepage.com/spring-4/spring-4-mvc-internationalization-i18n-and-localization-l10n-annotation-example
Create new exception
public abstract class BaseLocalizedException extends RuntimeException {
public String getLocalizedMessageKey() {
return "exception.objectNotFound"
}
public abstract Object[] getLocalizedMessageArguments();
}
public class BusinessObjectNotFoundException extends BaseLocalizedException {
private String objectType;
public String getLocalizedMessageKey() {
return "exception.objectNotFound"
}
public Object[] getLocalizedMessageArguments() {
return new Object[] {objectType};
}
}
Service layer
Throwing & catching Technical Exception
Anytime you catch technical exception you wrap it into business exception and
throw it in service layer.
Throwing Business Exception
You have to throw all business exception from service layer (in some cases
they could be throw from controller layer as well e.g. form validation)
Options for Exceptions handling
● per Exception
● per Controller
● globally
@ResponseStatus annotation
Unhandled exception causes server to return HTTP 500 response
Exceptions annotated with @ResponseStatus - when not handled - will return
chosen HTTP response accordingly to settings.
@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order") // 404
public class OrderNotFoundException extends RuntimeException {
// ...
}
@ResponseStatus annotation
Controller:
@RequestMapping(value="/orders/{id}", method=GET)
public String showOrder(@PathVariable("id") long id, Model model) {
Order order = orderRepository.findOrderById(id);
if (order == null) throw new OrderNotFoundException(id);
model.addAttribute(order);
return "orderDetail";
}
For specific controller …
@Controller
public class ExceptionHandlingController {
// @RequestHandler methods
...
// Exception handling methods
// Convert a predefined exception to an HTTP Status code
@ResponseStatus(value=HttpStatus.CONFLICT, reason="Data integrity violation") // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void conflict() {
// Nothing to do …
}
… and globally
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do ...
}
}
Global Exception Handler
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "AuthenticationException")
@ExceptionHandler(AuthenticationException.class)
public void handleAuthenticationException(HttpServletRequest request,
AuthenticationException ex) {
logger.error("AuthenticationException: URL=" + request.getRequestURL(), ex);
}
}
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Logging strategy
Always log exception on at least warning level.
Log Technical Exception on service layer and Business Exception in Global
Exception Handler.
Logger - SLF4J + logback / log4j / java.util.
logging
SLF4J - Simple Logging Facade for Java - allows end user to plug-in the desired
logging framework at the deployment time.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
Comparison of logger frameworks
Log4j - logging library for Java [2000-2002] ( no info about bugs )
Logback - Logback is intended as a successor to the popular log4j project,
picking up where log4j leaves off. [2006-now ] ( 324 unresolved )
Log4j 2 - Apache Log4j 2 is an upgrade to Log4j that provides significant
improvements over its predecessor, Log4j 1.x, and provides many of the
improvements available in Logback while fixing some inherent problems in
Logback's architecture. - [2012-now] (276 unresolved issues)
Read more
● http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2
● http://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial-with-examples-and-
best-practices.html
● http://archive.oreilly.com/pub/a/onjava/2006/01/11/exception-handling-framework-for-j2ee.html?
page=1
● http://www.javaworld.com/article/2071961/java-web-development/exception-management-and-
error-tracking-in-j2ee.html
● http://mariuszprzydatek.com/2013/07/29/spring-localized-exception-handling-in-rest-api/
● https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
● http://logback.qos.ch/manual/appenders.html

Weitere ähnliche Inhalte

Was ist angesagt?

jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 

Was ist angesagt? (20)

Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Core
Spring CoreSpring Core
Spring Core
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Hibernate
HibernateHibernate
Hibernate
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 

Andere mochten auch (6)

Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
exception handling
exception handlingexception handling
exception handling
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
String Handling
String HandlingString Handling
String Handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 

Ähnlich wie Exception handling

Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述
fangjiafu
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
funkatron
 

Ähnlich wie Exception handling (20)

Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult CasesPositive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
Positive Hack Days. Goltsev. Web Vulnerabilities: Difficult Cases
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Spring training
Spring trainingSpring training
Spring training
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
ERRest - Designing a good REST service
ERRest - Designing a good REST serviceERRest - Designing a good REST service
ERRest - Designing a good REST service
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
 

Mehr von Anna Pietras (10)

Start stop-continue
Start stop-continueStart stop-continue
Start stop-continue
 
Fluent API for selenium - options
Fluent API for selenium  - optionsFluent API for selenium  - options
Fluent API for selenium - options
 
Feedback
FeedbackFeedback
Feedback
 
Building RESTful API
Building RESTful APIBuilding RESTful API
Building RESTful API
 
Dlaczego (i jak) się uczyć
Dlaczego (i jak) się uczyćDlaczego (i jak) się uczyć
Dlaczego (i jak) się uczyć
 
Mapping in Java Options
Mapping in Java OptionsMapping in Java Options
Mapping in Java Options
 
Be a rockstar!
Be a rockstar!Be a rockstar!
Be a rockstar!
 
Global competetiveness of airlines
Global competetiveness of airlinesGlobal competetiveness of airlines
Global competetiveness of airlines
 
T mobile international cooperation
T mobile international cooperationT mobile international cooperation
T mobile international cooperation
 
My stories
My storiesMy stories
My stories
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

Exception handling

  • 2. Exception Handling - general rules - use exception only for exceptional situation. Creating an exception in Java is expensive and hence you should not do it just for testing if something is present, valid or permitted. In the latter case design your API to return this as a regular result. - every exception has to be logged in specific file to provide necessary information for “service desk” - decide what is the type of exception: - Business Exception - caused by invalid behavior of user, which need to be shown to him with specific message. - Technical Exception - caused by unexpected and exotic situation, are unchecked and try-catch is needed! This exception should be wrapped into Business Exception (Runtime exception), which could be shown to user as “system occur some technical problem, please try later”.
  • 3. Exception Handling - general rules - all exceptions should be named in specific and easy to understand way describe what unusual situation happened. Name suffix should be Exception. Examples: ObjectNotFoundException, IllegalArgumentException, MissingMetricException, DataValidationException … - Runtime exceptions have to be represented by specific status - proper for each situation.
  • 4. Exception Handling - http status ● 304 Not Modified - Used when HTTP caching headers are in play ● 400 Bad Request - The request is malformed, such as if the body does not parse ● 401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser ● 403 Forbidden - When authentication succeeded but authenticated user doesn't have access to the resource ● 404 Not Found - When a non-existent resource is requested ● 405 Method Not Allowed - When an HTTP method is being requested that isn't allowed for the authenticated user ● 500 Internal Server Error - when server has internal error, usually some technical or configuration problem ● … more if necessary
  • 5. global exception handler/controller layer service layer Exception workflow create exception create bundles throw & catch Technical Exception throw Business Exception handle Business Exception REST API Return response with proper HTTP status and message Client Show view with proper message log log User
  • 7. Create proper language versions. //exception.properties exception.objectNotFound= Cannot find object of type {0} //exception_pl.properties exception.objectNotFound= Nie znaleziono obiektu typu {0} http://www.mkyong.com/spring/spring-resource-bundle-with-resourcebundlemessagesource-example/
  • 8. Register bundles as @Bean @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("/exception"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } Note the basename is filepath of base msg file without .properties extension http://www.concretepage.com/spring-4/spring-4-mvc-internationalization-i18n-and-localization-l10n-annotation-example
  • 9. Create new exception public abstract class BaseLocalizedException extends RuntimeException { public String getLocalizedMessageKey() { return "exception.objectNotFound" } public abstract Object[] getLocalizedMessageArguments(); } public class BusinessObjectNotFoundException extends BaseLocalizedException { private String objectType; public String getLocalizedMessageKey() { return "exception.objectNotFound" } public Object[] getLocalizedMessageArguments() { return new Object[] {objectType}; } }
  • 10. Service layer Throwing & catching Technical Exception Anytime you catch technical exception you wrap it into business exception and throw it in service layer. Throwing Business Exception You have to throw all business exception from service layer (in some cases they could be throw from controller layer as well e.g. form validation)
  • 11. Options for Exceptions handling ● per Exception ● per Controller ● globally
  • 12. @ResponseStatus annotation Unhandled exception causes server to return HTTP 500 response Exceptions annotated with @ResponseStatus - when not handled - will return chosen HTTP response accordingly to settings. @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order") // 404 public class OrderNotFoundException extends RuntimeException { // ... }
  • 13. @ResponseStatus annotation Controller: @RequestMapping(value="/orders/{id}", method=GET) public String showOrder(@PathVariable("id") long id, Model model) { Order order = orderRepository.findOrderById(id); if (order == null) throw new OrderNotFoundException(id); model.addAttribute(order); return "orderDetail"; }
  • 14. For specific controller … @Controller public class ExceptionHandlingController { // @RequestHandler methods ... // Exception handling methods // Convert a predefined exception to an HTTP Status code @ResponseStatus(value=HttpStatus.CONFLICT, reason="Data integrity violation") // 409 @ExceptionHandler(DataIntegrityViolationException.class) public void conflict() { // Nothing to do … }
  • 15. … and globally @ControllerAdvice class GlobalControllerExceptionHandler { @ResponseStatus(HttpStatus.CONFLICT) // 409 @ExceptionHandler(DataIntegrityViolationException.class) public void handleConflict() { // Nothing to do ... } }
  • 16. Global Exception Handler @ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class); @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "AuthenticationException") @ExceptionHandler(AuthenticationException.class) public void handleAuthenticationException(HttpServletRequest request, AuthenticationException ex) { logger.error("AuthenticationException: URL=" + request.getRequestURL(), ex); } } https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
  • 17. Logging strategy Always log exception on at least warning level. Log Technical Exception on service layer and Business Exception in Global Exception Handler.
  • 18. Logger - SLF4J + logback / log4j / java.util. logging SLF4J - Simple Logging Facade for Java - allows end user to plug-in the desired logging framework at the deployment time. import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); } }
  • 19. Comparison of logger frameworks Log4j - logging library for Java [2000-2002] ( no info about bugs ) Logback - Logback is intended as a successor to the popular log4j project, picking up where log4j leaves off. [2006-now ] ( 324 unresolved ) Log4j 2 - Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture. - [2012-now] (276 unresolved issues)
  • 20. Read more ● http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2 ● http://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial-with-examples-and- best-practices.html ● http://archive.oreilly.com/pub/a/onjava/2006/01/11/exception-handling-framework-for-j2ee.html? page=1 ● http://www.javaworld.com/article/2071961/java-web-development/exception-management-and- error-tracking-in-j2ee.html ● http://mariuszprzydatek.com/2013/07/29/spring-localized-exception-handling-in-rest-api/ ● https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc ● http://logback.qos.ch/manual/appenders.html