SpringMVC异常处理配置实例

1.首先自定义异常类实现SimpleMappingExceptionResolver接口

public class PlatformMappingExceptionResolver extends

SimpleMappingExceptionResolver {

static Logger logger = LoggerFactory.getLogger(PlatformMappingExceptionResolver.class);

@Override

protected ModelAndView doResolveException(HttpServletRequest request,

HttpServletResponse response, Object handler, Exception ex) {

 

String viewName = determineViewName(ex, request);

// vm方式返回

if (viewName != null) {

if (!( request.getHeader("accept").indexOf("application/json") > -1 || ( request

.getHeader("X-Requested-With") != null && request

.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1 ) )) {

// 非异步方式返回

Integer statusCode = determineStatusCode(request, viewName);

if (statusCode != null) {

applyStatusCodeIfPossible(request, response, statusCode);

}

// 跳转到提示页面

ModelAndView view = new ModelAndView();

view.setViewName(viewName);

view.addObject("basePath", GlobalConfigHolder.getProperty("basePath"));

view.addObject("exception",ex);

return view;

} else {

// 异步方式返回

try {

PrintWriter writer = response.getWriter();

writer.write(ExceptionI18Message.getLocaleMessage(ex.getMessage()));

response.setStatus(404, ExceptionI18Message.getLocaleMessage(ex.getMessage()));

    logger.error(getTrace(ex));

writer.flush();

} catch ( Exception e ) {

 

e.printStackTrace();

}

// 不进行页面跳转

return null;

 

}

} else {

return null;

}

}

public static String getTrace(Throwable t) {

        StringWriter stringWriter= new StringWriter();

        PrintWriter writer= new PrintWriter(stringWriter);

        t.printStackTrace(writer);

        StringBuffer buffer= stringWriter.getBuffer();

        return buffer.toString();

    }

}

public class BusinessException extends Exception {

private static final long serialVersionUID = 1L;

 

public BusinessException() {

 

}

 

public BusinessException(String message) {

super(message);

}

 

public BusinessException(Throwable cause) {

super(cause);

}

 

public BusinessException(String message, Throwable cause) {

super(message, cause);

}

}

参考资料:

http://blog.csdn.net/lcore/article/details/42126299

http://gaojiewyh.iteye.com/blog/1297746

 

2.在springmvc的dispatcherServlet.xml中进行如下配置

<!--配置异常映射路径,ajax提示 -->

<bean id="exceptionResolver"

class="com.cisdi.ecis.common.exception.PlatformMappingExceptionResolver">

<property name="exceptionMappings">

<props>

<prop key="com.cisdi.ecis.common.exception.BusinessException">error/error</prop>

<prop key="java.lang.Exception">error/error</prop>

</props>

</property>

</bean>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值