coding_idiot
coding_idiot

Reputation: 13734

How to validate JSON being sent to the action using Struts 2 JSON Plugin without throwing exception?

Suppose, there's a Double variable in an action class, and if the value is sent in the request body, something like

{"dblField":""}

and the interceptorStack looks like :

<action name="save" class="actions.MyAction" method="save">
    <interceptor-ref name="jsonValidationWorkflowStack">
    </interceptor-ref>
    <!--<interceptor-ref name="loginStack"/>-->
   <!-- I've tried using each of the above two separately, but both failed -->
    <interceptor-ref name="json">
        <param name="enableSMD">true</param>
    </interceptor-ref>
    
    <result type="json" name="*">
        <param name="excludeProperties">
            idIo
        </param>
    </result>
</action>

then the action throws a NumberFormatException.

But this exception is not handled by the plugin, and hence, returns from the action by throwing an exception, which results in firing of global-exception-handler.

If the same request was sent using a query-string, ?dblField= then the action returns INPUT.

So, how can I make the json-plugin behave in the same way to return INPUT and set appropriate fieldErrors instead of throwing NumberFormatException and firing the globalExceptionHandler?

Upvotes: 2

Views: 1318

Answers (1)

Roman C
Roman C

Reputation: 1

You could place exception interceptor before your own interceptor instead of the json interceptor by extending json interceptor and override intercept method where you can catch errors. Then you can either add action errors or rethrow a custom exception which you can map in the action config or globally.

<exception-mapping exception="org.exceptionmapping.CustomException"
                             result="errorresult"/>

This way you can map all json only interceptor errors with your custom exception.

Upvotes: 2

Related Questions