Spring 統一管理輸出

使用  @ControllerAdvice  和 @ExceptionHandler 贊成處理 (註解可掃描的地方)java

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.wuage.ossserver.common.model.ReturnFormat;

@ControllerAdvice  
@EnableWebMvc
public class SpringExceptionHandler{  
    
    Logger logger = LoggerFactory.getLogger(this.getClass());  
  
    public static final String DEFAULT_ERROR_VIEW = "success";
    
    @ExceptionHandler(Exception.class)  
    @ResponseBody  
    public String defaultErrorHandler(HttpServletRequest req, Exception ex) throws Exception {
        logger.error("Error",ex);
        return ReturnFormat.retFailParam(ex.getMessage());
    }
    
    /*
     * 跳轉頁面
    @ExceptionHandler(Exception.class)  
    @ResponseBody  
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception ex) throws Exception {
        ModelAndView view=new ModelAndView(DEFAULT_ERROR_VIEW);
        return view;
    }
    */
  /* 部分會陷入 死循環,不能返回,使用攔截器
    //運行時異常
    @ExceptionHandler(MaxUploadSizeExceededException.class)  
    @ResponseBody  
    public String runtimeExceptionHandler(MaxUploadSizeExceededException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retFailParam("文件過大");
    } 
    */
   //運行時異常
    @ExceptionHandler(RuntimeException.class)  
    @ResponseBody  
    public String runtimeExceptionHandler(RuntimeException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retParam(1000, null);
    } 
    
    //空指針異常
    @ExceptionHandler(NullPointerException.class)  
    @ResponseBody  
    public String nullPointerExceptionHandler(NullPointerException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retParam(1001, null);
    }   
    //類型轉換異常
    @ExceptionHandler(ClassCastException.class)  
    @ResponseBody  
    public String classCastExceptionHandler(ClassCastException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retParam(1002, null);  
    }  

    //IO異常
    @ExceptionHandler(IOException.class)  
    @ResponseBody  
    public String iOExceptionHandler(IOException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retParam(1003, null); 
    }  
    //未知方法異常
    @ExceptionHandler(NoSuchMethodException.class)  
    @ResponseBody  
    public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retParam(1004, null);
    }  

    //數組越界異常
    @ExceptionHandler(IndexOutOfBoundsException.class)  
    @ResponseBody  
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {  
        logger.error("Error",ex);
        return ReturnFormat.retParam(1005, null);
    }
    
    //400錯誤
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseBody
    public String requestNotReadable(HttpMessageNotReadableException ex){
        logger.error("Error",ex);
        return ReturnFormat.retParam(400, null);
    }
    //400錯誤  參數類型不匹配
    @ExceptionHandler({TypeMismatchException.class})
    @ResponseBody
    public String requestTypeMismatch(TypeMismatchException ex){
        logger.error("參數類型不匹配,參數" + ex.getPropertyName() + "類型應該爲" + ex.getRequiredType(),ex);
        return ReturnFormat.retParam(400,null);
    }
    //400錯誤 缺乏參數異常
    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseBody  
    public String requestMissingServletRequest(MissingServletRequestParameterException ex){
        logger.error("缺乏必要參數,參數名稱爲" + ex.getParameterName(),ex);
        return ReturnFormat.retParam(400,null);
    }
    //405錯誤
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseBody
    public String request405(HttpRequestMethodNotSupportedException ex){
        logger.error("Error",ex);
        return ReturnFormat.retParam(405, null);
    }
    //406錯誤
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    @ResponseBody
    public String request406(HttpMediaTypeNotAcceptableException ex){
        logger.error("Error",ex);
        return ReturnFormat.retParam(406, null);
    }
    
    //500錯誤
    @ExceptionHandler({ConversionNotSupportedException.class,HttpMessageNotWritableException.class})
    @ResponseBody
    public String server500(RuntimeException runtimeException){
        logger.error("Error",runtimeException);
        return ReturnFormat.retParam(406, null);
    }
  
}

File 上傳 異常  MaxUploadSizeExceededException 有時候沒法生效,傳聞是 tomcat 緣由,可安以下方式修改web

<!-- 過濾文件攔截-->  
<mvc:interceptors>
   <mvc:interceptor>
     <!--方法名-->
     <mvc:mapping path="/**/upload.*"/>
       <bean class="com.wuage.ossserver.web.Interceptor.FileUploadInterceptor">
         <!--文件大小-->
         <property name="maxSize" value="5242880"/>
       </bean>
    </mvc:interceptor>
</mvc:interceptors>
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class FileUploadInterceptor implements HandlerInterceptor {
    
    private long maxSize;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request!=null && ServletFileUpload.isMultipartContent(request)) {
            ServletRequestContext ctx = new ServletRequestContext(request);
            long requestSize = ctx.contentLength();
            if (requestSize > maxSize) {
                throw new Exception("文件過大");
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    public void setMaxSize(long maxSize) {
        this.maxSize = maxSize;
    }
}
相關文章
相關標籤/搜索