views:

38

answers:

2

Hello,

I have a code which throws a specific type of exception like this:

throw new BadDataException("error message");

these kind of exceptions are thrown inside a method whose response type is json. I have a configuration for this exception type like this:

<global-exception-mappings>
     <exception-mapping result="badDataError" exception="mypackage.BadDataException" />
</global-exception-mappings>

<result name="badDataError" type="json">
    <param name="statusCode">500</param>
</result>

I'd like to add the exception message to the json response to show it to the user. Is there any way to map the exception message to the response when a 500 status code is returned. The ajax call would be something like this:

$.ajax(
{ 
   ...
    success: function(data, textStatus) {
         alert('Success'); 
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
         alert("Error");//I'd like to add here the reason (exception message)
    }
    ...
}
);

How can I add automatically the message of this exception to the HTTP 500 response? (if it is possible)

Thanks

A: 

This is finally how I've done it. I've added a errorMessage field to the HTTP 500 response in this way.

<result name="badDataError" type="httpheader">
                <param name="status">500</param>
                <param name="headers.errorMessage">${exception.message}</param>
</result>

and in the ajax request I recover the message like this.

error: function (XMLHttpRequest, textStatus, errorThrown) {
     var errorMessage = XMLHttpRequest.getResponseHeader('errorMessage'); 
     ....
}

Maybe there's a more elegant way to do this, but at least it works.

Javi
+1  A: 

Another option is to create a custom result type that both sets a 500 ISE status and returns a JSON response containing the error data. Then just map your exception to that result type in your struts.xml (just as you mapped it to the httpheader type in your example above).

Yet another option is to create an annotation for your Struts action methods that you intend to invoke via AJAX. Then, subclass the standard ExceptionMappingInterceptor and if the action method is annotated as @AjaxRequest (or whatever you call it), then you return a standard JSON response that contains the exception information. Otherwise, you fall through to the default behavior of mapping the result to some sort of page or result.

Personally, I prefer the latter approach.

Steven Benitez