Sunday, January 19, 2014

Filters to handle errors in application

I am having a spring web service application. I want to handle all the errors in that application and I want to return json with those errors.



This will not block client from expecting the response from the server. Somehow the server will return some json data with data or with error/exception.

Client can handle accordingly.

1) Add the filter in your web.xml file
    <filter>
         <filter-name>errorHandler</filter-name>
         <filter-class>com.test.ErrorHandler</filter-class>
    </filter>
    <filter-mapping>
         <filter-name>errorHandler</filter-name>
         <url-pattern>*</url-pattern>
    </filter-mapping>

2)  This is the class file of our ErrorHandler Filter

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletResponse;



import org.apache.log4j.Logger;

import org.codehaus.jackson.map.ObjectMapper;



// my exception class

import com.test.exception.CustomException;



public class ErrorHandler implements Filter {



        private static final String UTF_8 = "UTF-8";

        private static final String APPLICATION_JSON = "application/json";

        private static final Logger S_LOGGER= Logger.getLogger(ErrorHandler.class);

        private static boolean isDebugEnabled = S_LOGGER.isDebugEnabled();

        

        @Override

        public void init(FilterConfig filterConfig) throws ServletException {

        }



        @Override

        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

                try {

                        chain.doFilter(request, response);

                } catch (Exception e) {

                        if (isDebugEnabled) {

                                S_LOGGER.debug("Entering into the catch of ErrorHandler.doFilter()");

                        }

                        CustomException customException = new CustomException(e);

                        

                        ResponseInfo<Object> responseData = new ResponseInfo<Object>();

                        // Here construct the final response object - This is the custome method to construct a java object which will be a response

                        ResponseInfo<Object> finalOuptut = responseDataConstruct(responseData, customException, RESPONSE_STATUS_ERROR, ERR_CODE_000000);

                        

                        ObjectMapper mapper = new ObjectMapper();

                        // Convert it as Strng to return

                        String objectToReturn = mapper.writeValueAsString(finalOuptut);

                        

                        // It returns the json with data or error

                        HttpServletResponse res = (HttpServletResponse)response;

                        res.setStatus(res.SC_OK);

                        

                        response.setContentType(APPLICATION_JSON);

                        response.setCharacterEncoding(UTF_8);

                        PrintWriter out = response.getWriter();

                        out.print(objectToReturn);

                        out.flush();

                }

        }



        @Override

        public void destroy() {

        }

}

Thats it.

Normal Flow :

Whenever a error occurs(E.g NullPointerException) in a webapplication. Webpage will be displayed with that error plain. If it is webservice application, that error page will be returned as response.

Interceptors :
When ever a error occurs in application logic, response will come through the intereceptors.
We are adding our custom interceptor and If there is any error occurred we will return response(JSON) with that error. Client will handle accordingly.blog

--
Thank you.

Regards,
Kaleeswaran S

No comments:

Post a Comment