springmvc 的 exception自定义

本文详细介绍了如何在Spring MVC中实现自定义异常处理,包括异常映射、异常处理类的创建以及异常页面的配置。通过继承SimpleMappingExceptionResolver并自定义异常处理逻辑,确保了应用在遇到特定异常时能够返回合适的错误页面或JSON响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

全局性配置,用得比较多

1:继承SimpleMappingExceptionResolver

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {


 @Override
 protected ModelAndView doResolveException(HttpServletRequest request,
   HttpServletResponse response, Object handler, Exception ex) {
  // Expose ModelAndView for chosen error view.
  String viewName = determineViewName(ex, request);
  if (viewName != null) {// JSP格式返回
   if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
     .getHeader("X-Requested-With")!= null && request
     .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
    // 如果不是异步请求
    // Apply HTTP status code for error views, if specified.
    // Only apply it if we're processing a top-level request.
    Integer statusCode = determineStatusCode(request, viewName);
    if (statusCode != null) {
     applyStatusCodeIfPossible(request, response, statusCode);
    }
    return getModelAndView(viewName, ex, request);
   } else {// JSON格式返回
    try {
     PrintWriter writer = response.getWriter();
     writer.write(ex.getMessage());
     writer.flush();
    } catch (IOException e) {
     e.printStackTrace();
    }
    return null;

   }
  } else {
   return null;
  }
 }

}

 

2,在配置文件中webmvc-config.xml,加入异常处理bean

<bean id="exceptionResolver" class="com.xxx.common.exception.CustomSimpleMappingExceptionResolver">
    <property name="exceptionMappings">
      <props>  
    <prop key="com.xxx.common.exception.SystemException">500</prop>   其中的500是jsp名    500.jsp
          <prop key="com.xxx.common.exception.BusinessException">errorpage</prop> 其中的是jsp名    errorpage.jsp
    <prop key="java.lang.exception">500</prop>
       </props>
       </property>
 </bean>

其中BusinessException 为自定义异常类

public class BusinessException extends Exception

 

3,页面

必须有 isErrorPage="true"

例子:

<%@ page language="java"  pageEncoding="UTF-8" isErrorPage="true"%>
<%@ page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<title>XXX系统</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">

</head>
<body style="margin: 0;padding: 0;background-color: #f5f5f5;">
 <div id="center-div">
  
       服务器内部错误,请联系系统管理员!!    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    ${exception.message}
  
 </div>
</body>
</html>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值