Ravi Kant
Ravi Kant

Reputation: 4995

Spring MVC 3 User Defined Exception handling with User defined View

How to handle user defined exceptions (Custom Exception ex.: "BusinessException") in Spring MVC 3 with custom message and view name ?

For Example :

If i throw my own exception from Service layer it should be caught and should redirect to specified view with message, the view name may be same or different.

and i want to display message using properties file I searched in Google, but no luck.

Thanks.

Upvotes: 4

Views: 5514

Answers (3)

Ravi Kant
Ravi Kant

Reputation: 4995

Finally i found the answer of my question in detailed which i used in my application. In this post i have explained to handle exception in spring appllication at three level's

1.Error with specific code like 404

2.Error in Application

3.Any Exception in Ajax call

1.Error with specific code like 404

in web.xml

<error-page>
    <error-code>404</error-code>
    <location>/error</location>
</error-page>

specify one controller

@Controller
public class ErrorController {
      @RequestMapping(value="/error")
      public String handlePageNotFoundException(Exception ex,
          HttpServletResponse response) {
     return "error";
      }

}

error.jsp at the location specified in View Resolver

<span >
            An error has occured, please contact the support team.
</span>

2.Error in Application

Custome Exception Handler

@Component  
public class ExceptionHandler extends ExceptionHandlerExceptionResolver{
        @Autowired
        ApplicationContext context;

        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {

            TestException exception=null;
            if (ex instanceof DataAccessException) {
                exception = new TestException(context.getMessage("SQLException",
                        null, null));
            } else if (ex instanceof SQLException) {
                exception = new TestException(context.getMessage("SQLException",
                        null, null));
            } else if (ex instanceof java.net.UnknownHostException) {
                exception = new TestException(context.getMessage(
                        "UnknownHostException", null, null));
            } else if (ex instanceof IOException) {
                exception = new TestException(context.getMessage("IOException",
                        null,null));
            } else if (ex instanceof Exception) {
                exception = new TestException(context.getMessage("Exception",
                        null, null));
            } else if (ex instanceof Throwable) {
                exception = new TestException(context.getMessage("Throwable",
                        null, null));
            }



            if( isAjax(request) ) {
             return exception.asModelAndView();
           } 
            else
            {  ModelAndView modelAndView = new ModelAndView("TestExceptionPage");

            modelAndView.addObject("exception", exception);
            return modelAndView;
            }
        }
        private boolean isAjax(HttpServletRequest request) {
            return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        }





    }

Exception Pojo

public class TestException extends RuntimeException { 
    private String message;
    public TestException(){}

    public TestException(String message) {
        this.message = message;
    }
    public String getMessage(){
        return this.message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ModelAndView asModelAndView() {
        MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
        return new ModelAndView(jsonView, ImmutableMap.of("error", message));
    }

Exception jsp

    <h3><span>${exception.message}</span></h3>

3.Any Exception in Ajax call

Common.js

    function isError(data){
    if(typeof data.error == 'undefined')
        {
        return true;
        }
        return false;
}

Sample Ajax call in jsp

function customerNameAvail() {
    $.ajax({
      url: 'userNameAvail',
      data: ({email : $('#email').val()}),
      success: function(data) {
          if(isError(data))
          {

    if(data=="email already registered"){
     alert('customer Name already exist');
      }
          else{

             alert('customer Name Available');
              }
          }
          else
          {
        alert(data.error);
          }
      }
    });
}

Hope this will help for those who are looking for Exception Handling in spring 3.2.

Thanks

Upvotes: 2

andyb
andyb

Reputation: 43823

You can register a @Component to catch all exceptions by creating a bean with the default DispatcherServlet HANDLER_EXCEPTION_RESOLVER_BEAN_NAME and then add specific objects to a ModelAndView.

You can inject properties using @Value (Spring 3.0+) - see Spring properties (property-placeholder) autowiring for one example.

import org.springframework.web.servlet.*;
import org.springframework.validation.*;
import javax.servlet.http.*;

@Component(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

    @Value("${property.name}") private String injectedProperty;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mav = new ModelAndView("viewname");

        if (ex instanceof BusinessException) {
            mav.addObject("injectedProperty", injectedProperty);
        } else (ex instanceof BindException) {
            BindException bindEx = (BindException) ex;
            BindingResult result= bindEx.getBindingResult();

            // add errors from validation to mav
        }

        return mav;
    }
}

Upvotes: 0

Paul Whelan
Paul Whelan

Reputation: 16809

Have a look at the SimpleMappingExceptionResolver

<bean
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="com.example.exception.BusinessException">
                YourView
                    </prop>
            <prop key="java.lang.Exception">error</prop>
        </props>
    </property>
</bean>

Upvotes: 4

Related Questions