2

How can I implement a global exception handler for Apache Struts 2?

I'm using annotations (with struts.property) and NOT struts.xml.

I have got it to work for action-classes (at class and method level) but I would like something more global like a stand-alone class.

Can I for example use the ExeptionHandler from Struts 2? Hard to find documentation and examples.

Any ideas?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Staplerz
  • 85
  • 1
  • 10

1 Answers1

1

You can map exceptions to result that calls the action that would handle the exception.

<global-results>
    <result name="exception" type="chain">
        <param name="actionName">exceptionHandler</param>
        <param name="namespace">/</param>
    </result>
</global-results>
<global-exception-mappings>
    <exception-mapping exception="java.lang.Exception" result="exception" />
</global-exception-mappings>

References:

Marco Borchert
  • 1,038
  • 1
  • 11
  • 17
Roman C
  • 49,761
  • 33
  • 66
  • 176
  • 2
    But shouldn't that be placed inside struts.xml? The project I'm working on doesn't use the struts.xml (doesn't exist), it uses annotations. – Staplerz Mar 08 '16 at 23:50
  • @Staplerz annotations is an additional feature integrated with Struts2, it *doesn't* replace xml configuration. – Roman C Mar 09 '16 at 08:16
  • Oh I see, I'm new to struts2... I've found that there is an ExceptionHandler class in struts2 that could be defined in the struts.xml file as an element as according to following example: http://www.mkyong.com/struts/struts-global-custom-exception-example/ This is more like what I'm looking for. However I can't get it to work. Any ideas? – Staplerz Mar 09 '16 at 12:53
  • There's not `ExceptionHandler` class in Struts2, you can use `exception` interceptor with global exception mappings. The example is for Struts1.3.x, and it's a different framework than Struts2. – Roman C Mar 09 '16 at 13:01
  • Oh, it seems that it's part of struts 1. I will try your solution. Thanks! – Staplerz Mar 09 '16 at 13:17