Showing posts with label custom error exception. Show all posts
Showing posts with label custom error exception. Show all posts

Thursday, December 3, 2015

Grails Error Handling With Custom Http Status Code

First need to create a trait Groovy file as follows under src/groovy:

trait CustomExceptionHandler {
    /* Handle common exception */
    def handleException(Exception e) {
        handleCustomException(new CustomException(e.getMessage()))
    }

    /* Handle defined custom exception */
    def handleCustomException2(CustomException2 e) {
        handleCustomException(e)
    }

    /* Handle defined custom exception */
    def handleCustomException(CustomException e) {
        if (!CommonUtils.request) {
            // do something
        }
        else {
            CommonUtils.currentResponse.status = 220 (Custom response code)
            if(e.getStatusCode()) {
                CommonUtils.currentResponse.status = e.getStatusCode()
            }
            if (CommonUtils.request.xhr) {
                def error = [
                        type: "error",
                        message: e.getMessage()
                ]
                render error as JSON
            }
            else {
                render(view: "/error/error", model: [exception: e])
            }
        }
    }
}

Create a groovy class under src/groovy:

import org.springframework.web.context.request.RequestContextHolder
class CommonUtils {
    public static def getRequest() {
        def request = RequestContextHolder.getRequestAttributes()
        return request ? request.request : null
    }

    public static HttpServletResponse getCurrentResponse() {
        return WebUtils.retrieveGrailsWebRequest().getCurrentResponse()
    }
}

Exception Types (Reside in src/groovy):

class CustomException extends RuntimeException {

}
class CustomException2 extends CustomException {

}

How controller can use this feature:

class Controller1 implements CustomExceptionHandler {
    def index() {
        throw new Exception("Common exception")
    }

    def index2() {
        throw new CustomException("Defined custom exception")
    }

    def index3() {
        someService.index3()
    }

    def index4() {
        someService.index4()
    }
}

Exception thrown from service bahave same as from controller

class SomeService {
    def index3() {
        throw new Exception("Common exception")
    }

    def index4() {
        throw new CustomException("Defined custom exception")
    }
}

Friday, September 19, 2014

Spring MVC - Custom Exception Handling & Send Appropriate Error Code

Download full source code


Create a custom exception handler class as follows:


package com.pkm.maven.exception;

public class SpringException extends RuntimeException {
    private String exceptionMsg;
    
    public SpringException(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }
    
    public String getExceptionMsg() {
        return this.exceptionMsg;
    }
    
    public void setExceptionMsg(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }
}

Add following lines of code to your XXX-servlet.xml under WEB-INF


<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="com.pkm.maven.exception.SpringException">ExceptionPage</prop>
        </props>
    </property>
    <property name="defaultErrorView" value="error"/>
</bean>

Create a jsp page named 'ExceptionPage.jsp' defined in previous XXX-servlet.xml file under WEB-INF folder.


<h3 class="error">${exception.exceptionMsg}</h3>

Also create a file named 'error.jsp' under WEB-INF/jsp/ folder


<h3>General Error Page</h3>

Now time to throw custom exception

From method1 & method2 i am throwing my custom error so rendering my custom error page 'ErrorPage.jsp' & in method4, I am not throwing any exception but when invoking the line 'nullString.length()', it automatically throwing general exception, so rendering 'error.jsp' as defined in XXX-servlet.xml.


package com.pkm.maven.controller;

import com.pkm.maven.exception.SpringException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 * Controller action would be like this
 * public (ModelAndView | Map | String | void) actionName(HttpServletRequest, HttpServletResponse [,HttpSession] [,CommandObject]);
 * @author Pritom K Mondal
 */

public class CustomerController extends MultiActionController {    
    public ModelAndView method1(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        throw new SpringException("Error from customer controller and method1() action.");
        //return new ModelAndView("CustomerPage", "msg", "method1() method"); 
    }
 
    public ModelAndView method2(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        throw new Exception("Error from customer controller and method2() action.");
        //return new ModelAndView("CustomerPage", "msg", "method2() method"); 
    }
 
    public ModelAndView method3(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        return new ModelAndView("CustomerPage", "msg", "method3() method"); 
    }
 
    public ModelAndView method4(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String nullString = null;
        Integer length = nullString.length();
        return new ModelAndView("CustomerPage", "msg", "method4() method"); 
    }
}

Output would be like this in browser if you browse 'customer/method1' or 'customer/method2':


Output would be like this in browser if you browse 'customer/method4':