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

(1)建共用的异常处理器 CustomExceptionResolver
package com.ggs.mstd.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.ognl.OgnlException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ggs.mstd.CustomException.CustomException;
import com.ggs.mstd.CustomException.RequestUtil;
import com.ggs.mstd.CustomException.ResponseData;

@Controller
public class CustomExceptionResolver {

   

    /** @author wenfei.fang@hand - china.com
     * 处理控制层所有异常.
     * @param exception  未捕获的异常
     * @param request  HttpServletRequest
     * @return ResponseData(BaseException 被处理) 或者 ModelAndView(其他 Exception ,500错误)
     */
    @ExceptionHandler (value = { Exception. class })
    public @ResponseBody   Object exceptionHandler(Exception exception , HttpServletRequest request , HttpServletResponse response ) {
       /*判断请求类型是不是ajax的*/
      if (RequestUtil.isAjaxRequest( request )) {
           /*如果是Ajax请求将错误信息返回到ajax date*/
            Throwable thr = getRootCause( exception );
            ResponseData res = new ResponseData();
            if ( thr instanceof CustomException) {
               /*如果自定义的错误显示自定义的错误类型*/
              CustomException be = (CustomException) thr ;
               res .findMessage( be .getCode());
               res .setCode( be .getCode());
                res .setMessage( be .getMessage());
            } else
               /*如果不是自定义的错误显示系统性错误或同一错误*/
                  res .findMessage(ResponseData. SYSTEM_EXCEPTION );
                res .setMessage( thr .getMessage());
            }
            return res ;      
        } else {
           /*如果不是Ajax的重从定向到错误界面*/
            return new ModelAndView( "redirect:/categoryAttribute" );
        }
    }
    private Throwable getRootCause(Throwable throwable ) {
        while ( throwable .getCause() != null ) {
            throwable = throwable .getCause();
        }
        if ( throwable instanceof OgnlException && ((OgnlException) throwable ).getReason() != null ) {
            return getRootCause(((OgnlException) throwable ).getReason());
        }
        return throwable ;
    }
}

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

package com.ggs.mstd.CustomException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wenfei.fang
 *
 *         2016年11月11日
 */
public final class RequestUtil {

    public static final String X_REQUESTED_WIDTH = "X-Requested-With" ;
    public static final String XML_HTTP_REQUEST = "XMLHttpRequest" ;

    private RequestUtil() {
    }

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

    public static String getCookieValue(HttpServletRequest request , String name ) {
        Cookie[] cookies = request .getCookies();
        if ( cookies != null ) {
            for (Cookie cookie : cookies ) {
                String cookieName = cookie .getName();
                if ( cookieName .equals( name )) {
                    return cookie .getValue();
                }
            }
        }
        return null ;
    }
}

(3)建立一个类 继承 Exception

public abstract class CustomException extends Exception {

    private static final long serialVersionUID = 1L;

    // e.g. ORDER_FROZEN
    private String code ;

    private String descriptionKey ;

    private Object[] parameters ;

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

    public String getCode() {
        return code ;
    }

    public String getDescriptionKey() {
        return descriptionKey ;
    }

    public Object[] getParameters() {
        return parameters ;
    }

    public void setCode(String code ) {
        this . code = code ;
    }

    public void setDescriptionKey(String descriptionKey ) {
        this . descriptionKey = descriptionKey ;
    }

    public void setParameters(Object[] parameters ) {
        this . parameters = parameters ;
    }

}


(4)错误处理类


/**
 * 数据返回对象.
 *
 * @author wenfei.fang@hand - china.com
 */
public class ResponseData{

     
      public static final String SYSTEM_EXCEPTION = "Please contact the administrator." ;
      public static final String MSG_ERROR_APPROVE_COMMENTS = "msg error approve comments" ;
     
      public   void findMessage(String code ){
           this . message = code == null ? SYSTEM_EXCEPTION : code ;
     }
     
     
    // 返回状态编码
 
    private String code ;

    // 返回信息
   
      private String message ;

    public String getCode() {
           return code ;
     }

      public void setCode(String code ) {
           this . code = code ;
     }

      public String getMessage() {
           return message ;
     }

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










你可能感兴趣的:(ajax和普通请求使用spring mvc在controller中的异常统一处理)