9.1. Simplifying Exception Processing in an Action
Problem
You want to reduce the number of
try . . .
catch blocks within your Action classes.
Solution
Remove the exception-handling
code from your Action,
and define global and local exception handlers in your
struts-config.xml
file, as shown in Example 9-1.
Example 9-1. Global and local exception handling (partial)
...
<global-exceptions>
<exception key="error.unknown.user"
type="com.oreilly.strutsckbk.ch09.UnknownUserException"
path="/securityError.jsp"/>
</global-exceptions>
...
<action-mappings>
<action path="/Login"
type="com.oreilly.strutsckbk.ch09.LoginAction"
scope="request"
name="LoginForm"
validate="true"
input="/login.jsp">
<exception key="error.password.match"
type="com.oreilly.strutsckbk.ch09.PasswordMatchException">
<forward name="success" path="/login_success.jsp"/>
</action>
...Discussion
Prior to Struts 1.1, the handling of exceptions was left to the
devloper's devices. Exceptions returned from calls
to the business layer from an Action had to be
handled individually in your code. Because the perform(
) method of Struts 1.0 only allowed you to throw
IOException and
ServletException, you didn't have
much choice in the matter:
public ActionForward perform( ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...Any checked exception thrown within the body of perform() had to be caught and handled. In some cases, it was appropriate to catch ...