博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 统一管理输出
阅读量:6817 次
发布时间:2019-06-26

本文共 6702 字,大约阅读时间需要 22 分钟。

hot3.png

使用  @ControllerAdvice  和 @ExceptionHandler 同意处理 (注解可扫描的地方)

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  @EnableWebMvcpublic 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 原因,可安如下方式修改

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;    }}

 

转载于:https://my.oschina.net/u/943316/blog/860135

你可能感兴趣的文章
java5:运算
查看>>
防火墙配置IPsec ***
查看>>
codepro-Similar code compare
查看>>
Linux一些命令
查看>>
syn 同步!
查看>>
安装php扩展sphinx
查看>>
党援之众,无竞大义。群迷之中,无辩正论。
查看>>
svn http服务配置(1)
查看>>
Linux expect 用法
查看>>
shell脚本启动关闭tomcat,查看日志和备份项目
查看>>
玩转树莓派-RaspBerry,使用Python开发定制界面
查看>>
qt输出支持的数据库驱动
查看>>
OpenCV3中的机器学习算法
查看>>
96Boards(410C)中的Docker使用方法
查看>>
swift 里 1..2 和 1...2 的区别【chinaswift】
查看>>
我的友情链接
查看>>
有一种感情, 不叫爱情
查看>>
液晶屏幕清洗千万不要做的三种方法
查看>>
HttpServletRequest cannot be resolved to a type
查看>>
myBtatis --开篇
查看>>