4

如何使用自定义消息和视图名称在 Spring MVC 3 中处理用户定义的异常(自定义异常例如:“BusinessException”)?

例如 :

如果我从服务层抛出我自己的异常,它应该被捕获并应该重定向到带有消息的指定视图,视图名称可能相同或不同。

我想使用我在谷歌搜索的属性文件显示消息,但没有运气。

谢谢。

4

3 回答 3

4

看看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>
于 2013-04-18T08:06:50.423 回答
2

最后,我详细找到了我在应用程序中使用的问题的答案。在这篇文章中,我已经解释了在三个级别的春季应用程序中处理异常

1.特定代码错误,如404

2.申请错误

3.Ajax调用中的任何异常

1.特定代码错误,如404

在 web.xml 中

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

指定一个控制器

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

}

在 View Resolver 中指定的位置的 error.jsp

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

2.申请错误

客户异常处理程序

@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"));
        }





    }

异常波乔

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));
    }

异常jsp

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

3.Ajax调用中的任何异常

Common.js

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

jsp 中的示例 Ajax 调用

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);
          }
      }
    });
}

希望这对那些在 spring 3.2 中寻找异常处理的人有所帮助。

谢谢

于 2013-08-28T06:24:49.817 回答
0

您可以通过创建具有默认值的 bean来注册 a@Component以捕获所有异常,然后将特定对象添加到.DispatcherServlet HANDLER_EXCEPTION_RESOLVER_BEAN_NAMEModelAndView

您可以使用@Value(Spring 3.0+) 注入属性 - 请参阅Spring properties (property-placeholder) autowiring示例。

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;
    }
}
于 2013-04-18T08:21:20.840 回答