ajax和普通请求使用spring mvc在controller中的异常统一处理

来源:互联网 发布:怎么能做网络写手 编辑:程序博客网 时间:2024/05/20 19:16
(1)建共用的异常处理器 CustomExceptionResolver
packagecom.ggs.mstd.controller;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.ibatis.ognl.OgnlException;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.ExceptionHandler;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;
importcom.ggs.mstd.CustomException.CustomException;
importcom.ggs.mstd.CustomException.RequestUtil;
importcom.ggs.mstd.CustomException.ResponseData;

@Controller
publicclassCustomExceptionResolver {

   

   /**@authorwenfei.fang@hand-china.com
     * 处理控制层所有异常.
     *@paramexception  未捕获的异常
     *@paramrequest  HttpServletRequest
     *@returnResponseData(BaseException 被处理) 或者 ModelAndView(其他 Exception ,500错误)
     */
   @ExceptionHandler(value = { Exception.class})
   public@ResponseBody  Object exceptionHandler(Exceptionexception, HttpServletRequestrequest, HttpServletResponseresponse) {
      /*判断请求类型是不是ajax的*/
     if(RequestUtil.isAjaxRequest(request)) {
          /*如果是Ajax请求将错误信息返回到ajaxdate*/
            Throwablethr= getRootCause(exception);
            ResponseDatares=newResponseData();
           if(thrinstanceofCustomException) {
              /*如果自定义的错误显示自定义的错误类型*/
              CustomExceptionbe= (CustomException)thr;
              res.findMessage(be.getCode());
              res.setCode(be.getCode());
               res.setMessage(be.getMessage());
            }else
              /*如果不是自定义的错误显示系统性错误或同一错误*/
                 res.findMessage(ResponseData.SYSTEM_EXCEPTION);
               res.setMessage(thr.getMessage());
            }
           returnres;     
        }else{
          /*如果不是Ajax的重从定向到错误界面*/
           returnnewModelAndView("redirect:/categoryAttribute");
        }
    }
   privateThrowable getRootCause(Throwablethrowable) {
       while(throwable.getCause() !=null) {
           throwable=throwable.getCause();
        }
       if(throwableinstanceofOgnlException && ((OgnlException)throwable).getReason() !=null) {
           returngetRootCause(((OgnlException)throwable).getReason());
        }
       returnthrowable;
    }
}

(2)建立一个终态的类RequestUtil 判断请求类型

packagecom.ggs.mstd.CustomException;
importjavax.servlet.http.Cookie;
importjavax.servlet.http.HttpServletRequest;

/**
 *@authorwenfei.fang
 *
 *         2016年11月11日
 */
publicfinalclassRequestUtil {

   publicstaticfinalStringX_REQUESTED_WIDTH="X-Requested-With";
   publicstaticfinalStringXML_HTTP_REQUEST="XMLHttpRequest";

   privateRequestUtil() {
    }

   /**
     * 判断是否ajax请求.
     * 可以看到Ajax请求多了个 x-requested-with ,可以利用它,
     * request.getHeader("x-requested-with"); 为 null,则为传统同步请求,为 XMLHttpRequest,则为Ajax异步请求。
     *@paramrequest  HttpServletRequest
     *@return是否ajax请求.
     */
   publicstaticbooleanisAjaxRequest(HttpServletRequestrequest) {
        Stringxr=request.getHeader(X_REQUESTED_WIDTH);
       return(xr!=null&&XML_HTTP_REQUEST.equalsIgnoreCase(xr));
    }

   publicstaticString getCookieValue(HttpServletRequestrequest, Stringname) {
        Cookie[]cookies=request.getCookies();
       if(cookies!=null) {
           for(Cookiecookie:cookies) {
                StringcookieName=cookie.getName();
               if(cookieName.equals(name)) {
                   returncookie.getValue();
                }
            }
        }
       returnnull;
    }
}

(3)建立一个类 继承 Exception

publicabstractclassCustomExceptionextendsException {

   privatestaticfinallongserialVersionUID= 1L;

   // e.g. ORDER_FROZEN
   privateStringcode;

   privateStringdescriptionKey;

   privateObject[]parameters;

   /**
     * 不应该直接实例化,应该定义子类.
     *
     *@paramcode
     *            异常 code,通常与模块 CODE 对应
     *@paramdescriptionKey
     *            异常消息代码,系统描述中定义
     *@paramparameters
     *            如果没有参数,可以传 null
     */
   protectedCustomException(Stringcode, StringdescriptionKey, Object[]parameters) {
       super(descriptionKey);
       this.code=code;
       this.descriptionKey=descriptionKey;
       this.parameters=parameters;
    }

   publicString getCode() {
       returncode;
    }

   publicString getDescriptionKey() {
       returndescriptionKey;
    }

   publicObject[] getParameters() {
       returnparameters;
    }

   publicvoidsetCode(Stringcode) {
       this.code=code;
    }

   publicvoidsetDescriptionKey(StringdescriptionKey) {
       this.descriptionKey=descriptionKey;
    }

   publicvoidsetParameters(Object[]parameters) {
       this.parameters=parameters;
    }

}


(4)错误处理类


/**
 * 数据返回对象.
 *
 *@authorwenfei.fang@hand-china.com
 */
publicclassResponseData{

     
     publicstaticfinalStringSYSTEM_EXCEPTION="Please contact the administrator.";
     publicstaticfinalStringMSG_ERROR_APPROVE_COMMENTS="msg error approve comments";
     
     public voidfindMessage(Stringcode){
          this.message=code==null?SYSTEM_EXCEPTION:code;
     }
     
     
   // 返回状态编码
 
   privateStringcode;

   // 返回信息
   
     privateStringmessage;

   publicString getCode() {
          returncode;
     }

     publicvoidsetCode(Stringcode) {
          this.code=code;
     }

     publicString getMessage() {
          returnmessage;
     }

     publicvoidsetMessage(Stringmessage) {
          this.message=message;
     }
 
}
(5)Controller继承CustomExceptionResolver错误处理
@Controller
public class MegaFileReportController extends CustomExceptionResolver{
   @RequestMapping(value = "/api/megaFile/e")
public @ResponseBody String e(@RequestParam Map<String, Object> params) {
int m=1/0;
return null;
}
} 










1 0
原创粉丝点击