5.7. Exception Handling
5.7. Exception Handling
5.7. Exception Handling
RELEASE documentation
5.7.
5.7. Exception
Exception Handling
Handling
Table of Contents
Overview
Classification of exceptions
Exception handling methods
Detail
Types of exceptions
Business exception
Library exceptions that occurs during normal operation
System Exception
Unexpected System Exception
Fatal Errors
Framework exception in case of invalid requests
Exception Handling Patterns
When notifying partial redo of a use case (from middle)
When notifying redo of a use case (from beginning)
When notifying that the system or application is not in a normal state
When notifying that the request contents are invalid
When a fatal error has been detected
When notifying that an exception has occurred in the presentation layer (JSP etc.)
Basic Flow of Exception Handling
Basic flow when the Controller class handles the exception at request level
Basic flow when the Controller class handles the exception at use case level
Basic flow when the framework handles the exception at servlet level
Basic flow when the servlet container handles the exception at web application level
How to use
Application Settings
Common Settings
Domain Layer Settings
Application Layer Settings
Servlet Container Settings
Coding Points (Service)
Generating Business Exception
Generating System Exception
Catch the exception to continue the execution
Coding Points (Controller)
Method to handle exceptions at request level
Method to handle exception at use case level
Coding points (JSP)
Method to display messages on screen using MessagesPanelTag
Method to display system exception code on screen
How to use (Ajax)
Appendix
Exception handling classes provided by the common library
About SystemExceptionResolver settings
Attribute name of result message
Attribute name of exception code (message ID)
Header name of exception code (message ID)
Attribute name of exception object
Cache control flag of HTTP response
About HandlerExceptionResolverLoggingInterceptor settings
List of exception classes to be excluded from scope of logging
HTTP response code set by DefaultHandlerExceptionResolver
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 1/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
This chapter describes exception handling mechanism for web applications created using this guideline.
5.7.1. Overview
This section illustrates handling of exceptions occurring within the boundary of Spring MVC. The scope of
description is as follows:
1. Classification of exceptions
2. Exception handling methods
(2) Exceptions wherein cause The exceptions wherein cause 1. System Exception
cannot be resolved even if the cannot be resolved even if the 2. Unexpected System
user re-executes the operation user re-executes the operation, Exception
are handled using the 3. Fatal Errors
framework.
(3) Exceptions due to invalid The exceptions which occur due 1. Framework exception in case
requests from the client to invalid requests from the of invalid requests
client, are handled using the
framework.
Note
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 2/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
The exceptions which occur when the application is running, are handled using following 4 methods.
For details on flow of each handling method, refer to Basic Flow of Exception Handling.
(2) Use @ExceptionHandler Use this when exceptions are to be 1. When notifying redo of
annotation to carry out handled at use case (Controller) level. a use case (from
exception handling in For details, refer to Basic flow when beginning)
application code. the Controller class handles the
exception at use case level.
(3) Use HandlerExceptionResolver Use this in order to handle exceptions 1. When notifying that the
mechanism provided by the at servlet level. system or application is
framework to carry out When <mvc:annotation-driven> is not in a normal state
exception handling. specified, HandlerExceptionResolver
uses automatically registered class, 2. When notifying that the
and SystemExceptionResolver request contents are
provided by this framework. invalid
For details, refer to Basic flow when
the framework handles the exception
at servlet level.
(4) Use the error-page function of Use this in order to handle fatal errors 1. When a fatal error has
the servlet container to carry out and exceptions which are out of the been detected
exception handling. boundary of Spring MVC.
For details, refer to Basic flow when 2. When notifying that an
the servlet container handles the exception has occurred in
exception at web application level. the presentation layer
(JSP etc.)
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 3/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Note
Note
Note
This is a class for handling exceptions which are not handled by HandlerExceptionResolver which is registered
automatically when <mvc:annotation-driven> is specified. Therefore, the order of priority of this class should be set after
DefaultHandlerExceptionResolver.
Note
@ControllerAdvice made exception handling possible using @ExceptionHandler at servlet level. If methods with
@ExceptionHandler annotation are defined in a class with @ControllerAdvice annotation, then exception handling
carried out in the methods with @ExceptionHandler annotation can be applied to all the Controllers in Servlet. When
implementing the above in earlier versions, it was necessary to define methods with @ExceptionHandler annotation in
Controller base class and inherit each Controller from the base class.
Note
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 4/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
1. When logic other than determining the View name and HTTP response code is necessary for exception handling to
be carried out at servlet level, (If only determining View name and HTTP response code is sufficient, it can be
implemented using SystemExceptionResolver)
2. In case of exception handling carried out at servlet level, when response data is to be created by serializing the error
model (JavaBeans) in JSON or XML formats without using template engines such as JSP. (Used for error handling at
the time of creating Controller for AJAX or REST).
5.7.2. Detail
1. Types of exceptions
2. Exception Handling Patterns
3. Basic Flow of Exception Handling
(2) Library exceptions that occurs Amongst the exceptions that occur in framework and
during normal operation libraries, the exception which is likely to occur when the
system is operating normally.
(4) Unexpected System Exception Unchecked exception that does not occur when the
system is operating normally
(6) Framework exception in case of Exception to notify that the framework has detected
invalid requests invalid request contents
If the reservation date is past the deadline when making travel reservations
If a product is out of stock when it is ordered
etc ...
Note
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 5/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Amongst the exceptions that occur in the framework and libraries, the exception which is likely to occur when
the system is operating normally.
The exceptions that occur in the framework and libraries cover the exception classes in Spring Framework or
other libraries.
Situations such are below are pre-defined and hence need not be dealt by the system administrator.
Optimistic locking exception and pessimistic locking exception that occur if multiple users attempt to
update same data simultaneously.
Unique constraint violation exception that occurs if multiple users attempt to register same data
simultaneously.
etc ...
Note
Todo
Currently it has been found that unexpected errors occur if JPA(Hibernate) is used.
UncategorizedDataAccessException that occurs at the time of pessimistic locking error, is classified as system error,
hence handling it in the application is not recommended. However, there might be cases wherein this exception may
need to be handled. This exception can be handled since exception notifying the occurrence of pessimistic locking error
is saved as the cause of exception.
=>Further analysis
Exception to notify that a state which should not occur when the system is operating normally has been
detected.
This exception should be generated in application layer and domain layer.
The exception needs to be dealt by the system administrator.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 6/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
If the master data, directories, files, etc. those should have pre-existed, do not exist
Amongst the checked exceptions that occur in the framework, libraries, if exceptions classified as system
errors are caught (IOException during file operations etc.).
etc ...
Note
Unchecked exception that does not occur when the system is operating normally.
Action by system administrator or analysis by system developer is necessary.
Unexpected system exceptions should not be handled (try-catch) in the application code.
Note
Error to notify that a fatal problem impacting the entire system (application), has occurred.
Action/recovery by system administrator or system developer is necessary.
Fatal Errors (error that inherits java.lang.Error) must not be handled (try-catch) in the application code.
Note
Exception to notify that the framework has detected invalid request contents.
This exception occurs in the framework (Spring MVC).
The cause lies at client side; hence it need not be dealt by the system administrator.
Exception that occurs when a request path for which only POST method is permitted, is accessed using
GET method.
Exception that occurs when type-conversion fails for the values extracted from URI using @PathVariable
annotation.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 7/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
etc ...
Note
Class for which HTTP status code is “4XX” in the list given at HTTP response code set by
DefaultHandlerExceptionResolver.
There are 6 types of exception handling patterns based on the purpose of handling.
(1)-(2) should be handled at use case level and (3)-(6) should be handled at the entire system (application) level.
(2) When notifying redo of a use case 1. Business exception Application code Use case
(from beginning) 2. Library exceptions (@ExceptionHandler)
that occurs during
normal operation
(3) When notifying that the system or 1. System Exception Framework Servlet
application is not in a normal state 2. Unexpected System (Handling rules are
Exception specified in spring-
mvc.xml)
(5) When a fatal error has been 1. Fatal Errors Servlet container Web
detected (Handling rules are application
specified in web.xml)
(6) When notifying that an exception 1. All the exceptions Servlet container Web
has occurred in the presentation and errors that occur in (Handling rules are application
layer (JSP etc.) the presentation layer specified in web.xml)
When partial redo (from middle) of a use case is to be notified, catch (try-catch) the exception in the application
code of Controller class and carry out exception handling at request level.
Note
When an order is placed through a shopping site, if business exception notifying stock shortage occurs.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 8/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
In such a case, order can be placed if the no. of items to be ordered is reduced; hence display a screen on which no.
of items can be changed and prompt a message asking to change the same.
Figure - Handling method when notifying partial redo of a use case (from middle)
When redo of a use case (from beginning) is to be notified, catch the exception using @ExceptionHandler, and
carry out exception handling at use case level.
Note
At the time of changing the product master on shopping site (site for administrator), it has been changed by other
operator (in case of optimistic locking exception).
In such a case, the operation needs to be carried out after verifying the changes made by the other user; hence
display the front screen of the use case (for example: search screen of product master) and prompt a message
asking the user to perform the operation again.
Figure - Handling method when notifying redo of a use case (from beginning)
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 9/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
5.7.2.2.3. When notifying that the system or application is not in a normal state
When an exception to notify that system or application is not in a normal state is detected, catch the exception
using SystemExceptionResolver and carry out exception handling at servlet level.
Note
Examples for notifying that the system or application is not in a normal state
In case of a use case for connecting to an external system, if an exception occurs notifying that the external system
is blocked.
In such a case, since use case cannot be executed until external system resumes service, display the error screen,
and notify that the use case cannot be executed till the external system resumes service.
When searching master information with the value specified in the application, if the corresponding master
information does not exist.
In such a case, there is a possibility of bug in master maintenance function or of error (release error) in data input by
the system administrator; hence display the system error screen and notify that a system error has occurred.
etc ...
Figure - Handling method when an exception to notify that system or application is not in a normal state
is detected
When notifying that an invalid request is detected by the framework, catch the exception using
DefaultHandlerExceptionResolver, and carry out exception handling at servlet level.
Note
When a URI is accessed using GET method, while only POST method is permitted.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 10/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
In such a case, it is likely that the access has been made directly using the Favorites feature etc. of the browser;
hence display the error screen and notify that the request contents are invalid.
etc ...
Figure - Handling method when notifying that the request contents are invalid
When a fatal error has been detected, catch the exception using servlet container and carry out exception
handling at web application level.
5.7.2.2.6. When notifying that an exception has occurred in the presentation layer (JSP etc.)
When notifying that an exception has occurred in the presentation layer (JSP etc.), catch the exception using
servlet container and carry out exception handling at web application level.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 11/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Figure - Handling method when notifying an occurrence of exception in the presentation layer (JSP etc.)
1. Basic flow when the Controller class handles the exception at request level
2. Basic flow when the Controller class handles the exception at use case level
3. Basic flow when the framework handles the exception at servlet level
4. Basic flow when the servlet container handles the exception at web application level
5.7.2.3.1. Basic flow when the Controller class handles the exception at request level
In order to handle the exception at request level, catch (try-catch) the exception in the application code of the
Controller class.
Refer to the figure below:
It illustrates the basic flow at the time of handling a business exception
(org.terasoluna.gfw.common.exception.BusinessException) provided by this framework.
Log is output using interceptor (org.terasoluna.gfw.common.exception.ResultMessagesLoggingInterceptor)
which records that an exception holding the result message has occurred.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 12/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Figure - Basic flow when the Controller class handles the exception at request level
5.7.2.3.2. Basic flow when the Controller class handles the exception at use case level
In order to handle the exception at use case level, catch the exception using @ExceptionHandler of Controller
class.
Refer to the figure below.
It illustrates the basic flow at the time of handling an arbitrary exception (XxxException).
Log is output using interceptor
(org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptor). This interceptor records
that the exception is handled using HandlerExceptionResolver.
Figure - Basic flow when the Controller class handles the exception at use case level
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 13/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
3. Exception (XxxException) is generated in the Service class called from Controller class.
4. DispatcherServlet catches XxxException and calls ExceptionHandlerExceptionResolver.
5. ExceptionHandlerExceptionResolver calls exception handling method provided in Controller class.
6. Controller class generates message information (ResultMessage) and sets it to the Model for
screen display.
7. Controller class returns the View name.
8. ExceptionHandlerExceptionResolver returns the View name returned by the Controller.
9. HandlerExceptionResolverLoggingInterceptor calls ExceptionLogger and outputs logs (monitoring log and
application log) (at info, warn, error levels) corresponding to the exception code.
10. HandlerExceptionResolverLoggingInterceptor returns View name returned by
ExceptionHandlerExceptionResolver.
11. DispatcherServlet calls JSP that corresponds to the returned View name.
12. JSP acquires the message information (ResultMessage) using MessagesPanelTag and generates
HTML code for message display.
13. The response generated by JSP is displayed.
5.7.2.3.3. Basic flow when the framework handles the exception at servlet level
In order to handle the exception using the framework (at servlet level), catch the exception using
SystemExceptionResolver.
Refer to the figure below.
It illustrates the basic flow at the time of handling the system exception
(org.terasoluna.gfw.common.exception.SystemException) provided by this framework using
org.terasoluna.gfw.web.exception.SystemExceptionResolver.
Log is output using interceptor
(org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptor) which records the
exception specified in the argument of exception handling method.
Figure - Basic flow when the framework handles the exception at servlet level
4. A state equivalent to the system exception is detected in Service class; hence throw a SystemException.
5. DispatcherServlet catches SystemException, and calls SystemExceptionResolver.
6. SystemExceptionResolver acquires exception code from SystemException and sets it to
HttpServletRequest for screen display (6’).
7. SystemExceptionResolver returns the View name corresponding to SystemException.
8. HandlerExceptionResolverLoggingInterceptor calls ExceptionLogger and outputs logs (monitoring log and
application log) (at info, warn, error levels) corresponding to the exception code.
9. HandlerExceptionResolverLoggingInterceptor returns the View name returned by
SystemExceptionResolver.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 14/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
10. DispatcherServlet calls the JSP corresponding to the returned View name.
11. JSP acquires the exception code from HttpServletRequest and inserts it in HTML code for
message display.
12. The response generated by JSP is displayed.
5.7.2.3.4. Basic flow when the servlet container handles the exception at web application level
In order to handle exceptions at web application level, catch the exception using servlet container.
Fatal errors, exceptions which are not handled using the framework (exceptions in JSP etc.) and exceptions
occurred in Filter are to be handled using this flow.
Refer to the figure below.
It illustrates the basic flow at the time of handling java.lang.Exception by “error page”.
Log is output using servlet filter (org.terasoluna.gfw.web.exception.ExceptionLoggingFilter) which records
that an unhandled exception has occurred.
Figure - Basic flow when servlet container handles the exception at web application level
For exception handling classes provided by common library, refer to Exception handling classes provided by the
common library.
1. Application Settings
2. Coding Points (Service)
3. Coding Points (Controller)
4. Coding points (JSP)
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 15/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
The application settings required for using exception handling are shown below.
Further, these settings are already done in blank project. Hence, it will work only by doing changes given in
[Location to be customized for each project]section.
1. Common Settings
2. Domain Layer Settings
3. Application Layer Settings
4. Servlet Container Settings
1. Add bean definition of logger class (ExceptionLogger) which will output exception log.
applicationContext.xml
(2) Specify mapping between name of the exception to be handled and applicable “Exception
Code (Message ID)”.
In the above example, if the “BusinessException” is included in the class name of
exception class (or parent class), “w.xx.fw.8001” will be the “Exception code (Message
ID)” and if “ResourceNotFoundException” is included in the class name of exception class
(or parent class), “w.xx.fw.5001” will be the “Exception code (Message ID)”.
Note
The exception code is defined here for taking into account the case wherein message ID is
not specified in generated “BusinessException”, however, it is recommended that you specify
the “Exception Code (Message ID)” at the implementation side which generates the
“BusinessException” (this point is explained later). Specification of “Exception Code (Message
ID)” for “BusinessException” is an alternative measure in case it is not specified when
“BusinessException” occurs.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 16/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Note
Exception code is only to be output to log (It can also be fetched on screen). It is also possible
to create an ID which need not be in the format usually used to define IDs in Properties file,
but can be identified in the application. For example, MA7001 etc.
logback.xml
<appender name="MONITORING_LOG_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- (1) -->
<file>log/projectName-monitoring.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/projectName-monitoring-
%d{yyyyMMdd}.log</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<charset>UTF-8</charset>
<pattern><![CDATA[date:%d{yyyy-MM-dd HH:mm:ss}\tX-Track:%X{X-
Track}\tlevel:%-5level\tmessage:%msg%n]]></pattern>
</encoder>
</appender>
<logger name="org.terasoluna.gfw.common.exception.ExceptionLogger.Monitoring"
additivity="false"> <!-- (2) -->
<level value="error" /> <!-- (3) -->
<appender-ref ref="MONITORING_LOG_FILE" /> <!-- (4) -->
</logger>
(2) Specify logger definition for monitoring log. When creating ExceptionLogger, if any logger
name is not specified, the above settings can be used as is.
Warning
Specify false. If true is specified, the same log will be output by upper level logger (for
example, root).
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 17/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
<appender name="APPLICATION_LOG_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- (1) -->
<file>log/projectName-application.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/projectName-application-
%d{yyyyMMdd}.log</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<charset>UTF-8</charset>
<pattern><![CDATA[date:%d{yyyy-MM-dd HH:mm:ss}\tthread:%thread\tX-
Track:%X{X-Track}\tlevel:%-5level\tlogger:%-48logger{48}\tmessage:%msg%n]]>
</pattern>
</encoder>
</appender>
<root level="warn">
<appender-ref ref="STDOUT" />
<appender-ref ref="APPLICATION_LOG_FILE" /> <!-- (4) -->
</root>
(2) Specify logger definition for application log. When creating ExceptionLogger, if any logger
name is not specified, the above settings can be used as is.
Note
Rather than defining a separate appender for logging exceptions, it is recommended to use
the same appender which is used for logging in application code or framework. By using same
output destination, it becomes easier to track the process until an exception occurs.
(3) Specify the output level. In ExceptionLogger, 3 types of logs of info, warn, error are
output; however, the level specified should be as per the system requirements. This
guideline recommends info level.
[Location to be customized for each project]
(4) Log is transmitted to root since appender is not specified for the logger set in (2).
Therefore, specify an appender which will act as output destination. Here, it will be output
to “STDOUT” and “APPLICATION_LOG_FILE”.
[Location to be customized for each project]
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 18/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
xxx-domain.xml
(2) Inject the logger which outputs exception log. Specify “exceptionLogger” defined in
applicationContext.xml.
(3) Apply ResultMessagesLoggingInterceptor for the method of the Service class (with
@Service annotation).
Add to bean definition, the class (SystemExceptionResolver) used for handling the exceptions which are not
handled by HandlerExceptionResolver registered automatically when <mvc:annotation-driven> is specified. .
spring-mvc.xml
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 19/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--
(8) -->
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
(2) Inject the object that resolves exception code (Message ID). Specify
“exceptionCodeResolver” defined in applicationContext.xml.
(3) Specify the order of priority for handling. The value can be “3”. When <mvc:annotation-
driven> is specified, automatically registered class is given higher priority.
Hint
(4) Specify the mapping between name of the exception to be handled and View name.
In the above settings, if class name of the exception class (or parent class) includes
”.DataAccessException”, “common/error/dataAccessError” will be treated as View name.
If the exception class is “ResourceNotFoundException”,
“common/error/resourceNotFoundError” will be treated as View name.
[Location to be customized for each project]
(5) Specify the mapping between View name and HTTP status code.
In the above settings, when View name is “common/error/resourceNotFoundError”,
“404(Not Found)” becomes HTTP status code.
[Location to be customized for each project]
(7) Specify default value of HTTP status code to be set in response header. It is
recommended that you set “500”(Internal Server Error).
Warning
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 20/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
AOP settings and interceptor class (HandlerExceptionResolverLoggingInterceptor) in order to output the log of
exceptions handled by HandlerExceptionResolver should be added to bean definition.
spring-mvc.xml
class="org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptor">
<!-- (1) -->
<property name="exceptionLogger" ref="exceptionLogger" /> <!-- (2) -->
</bean>
<aop:config>
<aop:advisor advice-ref="handlerExceptionResolverLoggingInterceptor"
pointcut="execution(*
org.springframework.web.servlet.HandlerExceptionResolver.resolveException(..))" />
<!-- (3) -->
</aop:config>
(2) Inject the logger object which outputs exception log. Specify the “exceptionLogger”
defined in applicationContext.xml.
As per default settings, this class will not output the log for common library provided
org.terasoluna.gfw.common.exception.ResultMessagesNotificationException class
and its subclasses.
The reason the exceptions of the sub class of ResultMessagesNotificationException are
excluded from the log output is because their log output is carried out by
org.terasoluna.gfw.common.exception.ResultMessagesLoggingInterceptor.
If default settings need to be changed, refer to About
HandlerExceptionResolverLoggingInterceptor settings.
Filter class (ExceptionLoggingFilter) used to output log of fatal errors and exceptions that are out
of the boundary of Spring MVC should be added to bean definition and web.xml.
applicationContext.xml
(2) Inject the logger object which outputs exception log. Specify the “exceptionLogger”
defined in applicationContext.xml.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 21/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
web.xml
<filter>
<filter-name>exceptionLoggingFilter</filter-name> <!-- (1) -->
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-
class> <!-- (2) -->
</filter>
<filter-mapping>
<filter-name>exceptionLoggingFilter</filter-name> <!-- (3) -->
<url-pattern>/*</url-pattern> <!-- (4) -->
</filter-mapping>
(3) Specify the name of the filter to be mapped. The value specified in (1).
(4) Specify the URL pattern to which the filter must be applied. It is recommended that you
use /* for outputting log of fatal errors and exceptions that are out of the boundary of
Spring MVC.
Output Log
Add error-page definition for Servlet Container in order to handle error response
(HttpServletResponse#sendError) received through default exception handling functionality of Spring MVC, fatal
errors and the exceptions that are out of the boundary of Spring MVC.
web.xml
<error-page>
<!-- (1) -->
<error-code>404</error-code>
<!-- (2) -->
<location>/WEB-INF/views/common/error/resourceNotFoundError.jsp</location>
</error-page>
(2) Specify the file name. It should be specified with the path from Web application root. In
the above settings, “${WebAppRoot}/WEB-
INF/views/common/error/resourceNotFoundError.jsp” will be the View file.
[Location to be customized for each project]
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 22/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Add definitions in order to handle fatal errors and exceptions that are out of the boundary of Spring
MVC.
<error-page>
<!-- (3) -->
<location>/WEB-
INF/views/common/error/unhandledSystemError.html</location>
</error-page>
Note
If a fatal error occurs, there is high possibility of getting another error if the path of dynamic contents is specified.; hence
in location tag, it is recommended that you specify a path of static contents such as HTML and not dynamic
contents such as JSP.
Note
If an unexpected error response (HttpServletResponse#sendError) occurs after carrying out the above settings, there
may be cases wherein it cannot be determined what kind of error response occured.
Error screen specified in location tag is displayed; however if the cause of error cannot be identified from logs, it is
possible to verify the error response (HTTP response code) on screen by commenting out the above settings.
When it is necessary to individually handle the exceptions that are out of the boundary of Spring MVC, definition of each
exception should be added.
<error-page>
<!-- (4) -->
<exception-type>java.io.IOException</exception-type>
<!-- (5) -->
<location>/WEB-INF/views/common/error/systemError.jsp</location>
</error-page>
(5) Specify the file name. Specify it using a path from web application root. In above case,
“${WebAppRoot}/WEB-INF/views/common/error/systemError.jsp” will be the View file.
[Location to be customized for each project]
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 23/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Note
It is recommended that you generate the business exception by detecting violation of business rules in logic.
When it is required by the API specification of underlying base framework or existing layer of application, that
violation of business rule be notified through an exception, then it is OK to catch the exception and throw it as
business exception.
Use of an exception to control the processing flow lowers the readability of overall logic and thus may reduce
maintainability.
Warning
It is assumed that business exception is generated in Service by default. In AOP settings, log of business exception
occurred in class with @Service annotation, is being output. Business exceptions should not be logged in Controller
etc. This rule can be changed if needed in the project.
xxxService.java
...
@Service
public class ExampleExceptionServiceImpl implements ExampleExceptionService {
@Override
public String throwBisinessException(String test) {
...
// int stockQuantity = 5;
// int orderQuantity = 6;
Tip
For the purpose of explanation, xxxService.java logic is written in steps (2)-(4) as shown above, however it can also
be written in a single step.
xxx.properties
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 24/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
e.ad.od.5001 = Order number is higher than the stock quantity={0}. Change the order
number.
// stackTrace omitted
...
Displayed screen
Warning
It is recommended that you handle business exception in Controller and display a message on each business screen.
The above example illustrates a screen which is displayed when the exception is not handled in Controller.
try {
order(orderQuantity, itemId );
} catch (StockNotEnoughException e) { // (1)
throw new BusinessException(ResultMessages.error().add(
"e.ad.od.5001", e.getStockQuantity()), e); // (2)
}
(2) If the system is in an abnormal state, specify the exception code (message ID) as 1st
argument. Specify exception message as 2nd argument to generate SystemException.
In the above example, the value of variable “itemId” is inserted in message text.
Displayed screen
Note
It is desirable to have a common system error screen rather than creating multiple screens for system errors.
The screen mentioned in this guideline displays a (business-wise) message ID for system errors and has a fixed
message. This is because there is no need to inform the details of error to the operator and it is sufficient to only convey
that the system error has occured. Therefore, in order to enhance the response for inquiry against system errors, the
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 26/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Message ID which acts as a key for the message text is displayed on the screen, in order to make the analysis easier
for the development side. Displayed error screens should be designed in accordance with the UI standards of each
project.
try {
return new File(preUploadDir.getFile(), key);
} catch (FileNotFoundException e) { // (1)
throw new SystemException("e.ad.od.9007",
"not found upload file. file is [" + preUploadDir.getDescription() + "]."
e); // (2)
}
(2) Specify the exception code (message ID), message, Cause Exception (e) to generate
SystemException.
When it is necessary to catch the exception to continue the execution, the exception should be logged before
continuing the execution.
When fetching customer interaction history from external system fails, the process of fetching information other
than customer history can still be continued. This is illustrated in the following example.
In this example, although fetching of customer history fails, business process does not have to be stopped and
hence the execution continues.
@Inject
ExceptionLogger exceptionLogger; // (1)
// ...
// (4)
Customer customer = customerRepository.findOne(customerId);
// ...
(3) Output the handled exception to log. In the example, log method is being called; however
if the output level is known in advance
and if there is no possibility of any change in output level, it is ok to call info, warn, error
methods directly.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 27/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Warning
When log() is used in exceptionLogger, since it will be output at error level; by default, it will be output in
monitoring log also.
As shown in this example, if there is no problem in continuing the execution, and if monitoring log is
being monitored through application monitoring, it should be set to a level such that it will not get
monitored at log output level or defined such that it does not get monitored from the log content (log
message).
} catch (RestClientException e) {
exceptionLogger.info(e);
}
As per default settings, monitoring log other than error level will not be output. It is output in
application log as follows:
Handle the exception at request level and set the message related information to Model.
Then, by calling the method for displaying the View, generate the model required by the View and determine the
View name.
// omitted
// omitted
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 28/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
(4) Call the method for displaying the View at the time of error. Fetch the model and View
name required for View display and then return the View name to be displayed.
Handle the exception at use case level and generate ModelMap (ExtendedModelMap) wherein message related
information etc. is stored.
Then, by calling the method for displaying the View, generate the model required by the View and determine the
View name.
@ExceptionHandler(BusinessException.class) // (1)
@ResponseStatus(HttpStatus.CONFLICT) // (2)
public ModelAndView handleBusinessException(BusinessException e) {
ExtendedModelMap modelMap = new ExtendedModelMap(); // (3)
modelMap.addAttribute(e.getResultMessages()); // (4)
String viewName = top(modelMap); // (5)
return new ModelAndView(viewName, modelMap); // (6)
}
(2) Specify the HTTP status code to be returned to value attribute of @ResponseStatus
annotation. In the example, “409: Conflict” is specified.
(3) Generate ExtendedModelMap as an object to link the error information and model
information with View.
(5) Call the method to display the View at the time of error and fetch model and View name
necessary for View display.
(6) Generate ModelAndView wherein View name and Model acquired in steps (3)-(5) are
stored and then return the same.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 29/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
The example below illustrates implementation at the time of displaying exception code (message
ID) and fixed message at an arbitrary location.
<p>
<c:if test="${!empty exceptionCode}"> <!-- (1) -->
[${f:h(exceptionCode)}] <!-- (2) -->
</c:if>
<spring:message code="e.cm.fw.9999" /> <!-- (3) -->
</p>
Note
When a system exception occurs, it is recommended that you display a message which would only
convey that a system exception has occurred, without outputting a detailed message from which cause
of error can be identified or guessed.
On displaying a detailed message from which cause of error can be identified or guessed, the
vulnerabilities of system are likely to get exposed.
Note
When a system exception occurs, it is desirable to output an exception code (message ID) instead of a
detailed message.
By outputting the exception code (message ID), it is possible for development team to respond quickly
to the inquiries from system user.
Only a system administrator can identify the cause of error from exception code (message ID); hence
the risk of exposing the vulnerabilities of system is lowered.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 30/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
5.7.5. Appendix
In addition to the classes provided by Spring MVC, the classes for carrying out exception handling are being
provided by the common library.
The roles of classes are as follows:
Warning
(4) ExceptionLevel Interface for resolving exception level (log level) of exception class.
Resolver Exception level is a code for identifying the level of exception and is used
to switch the output level of log.
It is referenced from ExceptionLogger.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 31/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
(7) ResultMessages This is an interceptor class for logging an occurrence of exception which
LoggingInterceptor stores ResultMessages (sub exception of
ResultMessagesNotificationException).
Output all the logs at WARN level.
It is assumed that this Interceptor will be applied to the methods of class
with @Service annotation.
Log is output using ExceptionLogger.
(8) BusinessException This is an exception class to notify violation of business rules. This
exception should be generated in the logic of domain layer.
It inherits java.lang.RuntimeException; hence the transactions are rolled
back as per default behavior.
If you want to commit the transactions, this exception class needs to be
specified in noRollbackFor or noRollbackForClassName of
@Transactional annotation.
(9) Resource This is an exception class to notify that the specified resource (data) does
NotFoundException not exist in the system. This exception should mainly be generated in the
logic of domain layer.
It inherits java.lang.RuntimeException; hence the transactions are rolled
back as per default behavior.
(10) ResultMessages This is an abstract exception class to notify that the exception holds the
Notification result messages (ResultMessages), and BusinessException and
Exception ResourceNotFoundException inherit it in the common library.
It inherits java.lang.RuntimeException; hence the transactions are rolled
back as per default behavior.
If this exception class is inherited, log of warn level will be output by
ResultMessagesLoggingInterceptor.
(11) SystemException This is an exception class to notify a system or application error. This
exception should be generated in the logic of application layer or domain
layer.
It inherits java.lang.RuntimeException; hence the transactions are rolled
back as per default behavior.
(12) ExceptionCodeProvider This is an interface indicating that it has a role to hold the exception code;
it is implemented by SystemException in the common library.
If an exception class that implements this interface is created, it can be
used with the exception handling mechanism of ExceptionCodeResolver,
to use the exception code of this exception class as it is.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 32/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
(14) HandlerException This is an Interceptor class to output the log of exceptions handled by
ResolverLogging HandlerExceptionResolver.
Interceptor In this Interceptor class, the output level of log is switched based on the
classification of HTTP response code resolved by
HandlerExceptionResolver.
1. When it is “100-399”, log is output at INFO level.
2. When it is “400-499”, log is output at WARN level.
3. When it is “500-”, log is output at ERROR level.
4. When it is “-99”, log is not output.
By using this Interceptor, it is possible to output the log of all exceptions
which are within the boundary of Spring MVC.
Log is output using ExceptionLogger.
(15) ExceptionLogging This is a Filter class to output the log of fatal errors and exceptions that are
Filter out of the boundary of Spring MVC.
All logs are output at ERROR level.
When this Filter is used, fatal errors and all exceptions that are out of the
boundary of Spring MVC can be output to log.
Log is output using ExceptionLogger.
This section describes the settings which are not explained above. The settings should be performed depending
on the requirements.
(2) Attribute name of exceptionCode Specify the attribute name (String) exceptionCode
exception code Attribute used for setting the exception code
(message ID) (message ID) to HttpServletRequest.
This attribute name is used for
accessing the exception code
(message ID) in View(JSP).
(3) Header name of exceptionCode Specify the header name (String) X-Exception-Code
exception code Header used for setting the exception code
(message ID) (message ID) to response header of
HttpServletResponse.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 33/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Sr.
No. Field Name Property Name Description Default Value
(4) Attribute name of exceptionAttribute Specify the attribute name (String) exception
exception object used for setting the handled
exception object to Model.
This attribute name is used for
accessing the exception object in
View(JSP).
(5) List of handler mappedHandlers Specify the object list (Set) of Not specified
(Controller) handlers that use this
objects to be used ExceptionResolver. When specified,
as this Only the exceptions in the specified the operation is
ExceptionResolver handler objects will be handled. not guaranteed.
This setting should not be
specified.
(6) List of handler mappedHandlerClasses Specify the class list (Class[]) of Not specified
(Controller) handlers that use this
classes that use ExceptionResolver. When specified,
this Only the exceptions that occur in the the operation is
ExceptionResolver specified handler classes are not guaranteed.
handled.
This setting should not be
specified
(7) Cache control flag preventResponseCaching Set the flag (true: Yes, false: No) for false: No
of HTTP response cache control at the time of HTTP
response.
If true: Yes is specified, HTTP
response header to disable cache is
added.
If the message set by handling the exception using SystemExceptionResolver and the message set by handling
the exception in application code, both are to be output in separate messagesPanel tags in View(JSP), then
specify an attribute name exclusive to SystemExceptionResolver.
The example below illustrates settings and implementation when changing the default value to
“resultMessagesForExceptionResolver”.
spring-mvc.xml
<bean class="org.terasoluna.gfw.web.exception.SystemExceptionResolver">
jsp
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 34/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
(2) Specify attribute name that was set in SystemExceptionResolver, in message attribute
name (messagesAttributeName).
When default attribute name is being used in the application code, a different value should be set in order to
avoid duplication. When there is no duplication, there is no need to change the default value.
The example below illustrates settings and implementation when changing the default value to
“exceptionCodeForExceptionResolver”.
spring-mvc.xml
<bean class="org.terasoluna.gfw.web.exception.SystemExceptionResolver">
jsp
<p>
<c:if test="${!empty exceptionCodeForExceptionResolver}"> <!-- (2) -->
[${f:h(exceptionCodeForExceptionResolver)}] <!-- (3) -->
</c:if>
<spring:message code="e.cm.fw.9999" />
</p>
When default header name is being used, set a different value in order to avoid duplication. When there is no
duplication, there is no need to change the default value.
The example below illustrates settings and implementation when changing the default value to “X-Exception-
Code-ForExceptionResolver”.
spring-mvc.xml
<bean class="org.terasoluna.gfw.web.exception.SystemExceptionResolver">
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 35/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
<!-- omitted -->
</bean>
When default attribute name is being used in the application code, set a different value in order to avoid
duplication. When there is no duplication, there is no need to change the default value.
The example below illustrates settings and implementation when changing the default value to
“exceptionForExceptionResolver”.
spring-mvc.xml
<bean class="org.terasoluna.gfw.web.exception.SystemExceptionResolver">
jsp
<p>[Exception Message]</p>
<p>${f:h(exceptionForExceptionResolver.message)}</p> <!-- (2) -->
When header for cache control is to be added to HTTP response, specify true: Yes.
spring-mvc.xml
<bean class="org.terasoluna.gfw.web.exception.SystemExceptionResolver">
Note
If cache control flag of HTTP response is set to Yes, the following HTTP response header is output.
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 36/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
Cache-Control:no-store
Cache-Control:no-cache
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Pragma:no-cache
The settings when exception classes provided in the project are to be excluded from the scope of logging, are as
follows:
spring-mvc.xml
<bean id="handlerExceptionResolverLoggingInterceptor"
class="org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptor">
<property name="exceptionLogger" ref="exceptionLogger" />
<property name="ignoreExceptions">
<set>
<!-- (1) -->
<value>org.terasoluna.gfw.common.exception.ResultMessagesNotificationException</valu
e>
<!-- (2) -->
<value>com.example.common.XxxException</value>
</set>
</property>
</bean>
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 37/38
11/6/2019 5.7. Exception Handling — TERASOLUNA Global Framework Development Guideline 1.0.1.RELEASE documentation
The settings when all the exception classes are to be logged are as follows:
spring-mvc.xml
<bean id="handlerExceptionResolverLoggingInterceptor"
class="org.terasoluna.gfw.web.exception.HandlerExceptionResolverLoggingInterceptor">
<property name="exceptionLogger" ref="exceptionLogger" />
<!-- (3) -->
<property name="ignoreExceptions"><null /></property>
</bean>
HTTP
Sr. Status
No. Handled framework exceptions Code
(1) org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException 404
https://terasolunaorg.github.io/guideline/1.0.1.RELEASE/en/ArchitectureInDetail/ExceptionHandling.html 38/38