全局异常捕获实现

  @ControllerAdvice 注解   spring mvc异常统一处理 

package com.yylending.plms.common.exception;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yylending.plms.urge.base.Result;


/**
 * 自定义异常拦截机制
 *
 * @author chaijq
 * @date 2018/3/21 9:42
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        logError(req,e);
        //result.setRetMsg(e.getMessage());
        return Result.error();
    }
    /**
     * 会优先处理JsonException异常
     * 返回json格式
     */
    @ResponseBody
    @ExceptionHandler(value = LogicException.class)
    public Result jsonErrorHandler(HttpServletRequest req, LogicException e){
        logError(req,e);
        return Result.error(e.getCode(),e.getMessage());
    }
    
    /**
     * 捕捉任何参数不传所抛出的异常
     */
    @ResponseBody
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result doHttpMessageNotReadableException(HttpServletRequest req, HttpMessageNotReadableException e){
        logError(req,e);
        return Result.requestParamError();
    }

    /**
     * 捕捉请求类型不支持的异常
     */
    @ResponseBody
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Result doHttpRequestMethodNotSupportedException(HttpServletRequest req, HttpRequestMethodNotSupportedException e){
        logError(req,e);
        return Result.error(Result.ResultEnum.REQUEST_METHOD_ERROR.code, e.getMessage());
    }

   /**
    * 处理参数异常
    * @param request  请求
    * @param e   异常
    * @return 响应内容
    */
    @ResponseBody
   @ExceptionHandler({MethodArgumentNotValidException.class })
   protected Result doValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
      log.warn("uri={} | msg={} ", new Object[] { request.getRequestURI(), e.getMessage() });
      List<ObjectError> errors = e.getBindingResult().getAllErrors();
      String tips = "参数不合法";
      if (errors.size() > 0) {
         tips = errors.get(0).getDefaultMessage();
      }
      return Result.paramWarn(tips);
   }
    
    private static void logError(HttpServletRequest req, Object e){
        log.error("url:{}|error:{}",req.getRequestURI(),e);
    }

    /**
     * 初始化数据绑定(只针对form提交类型)
     * 1. 将所有传递进来的String进行HTML编码,防止XSS攻击
     * 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                try {
                    setValue(DateUtils.parseDate(text, new String[]{
                            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
                            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
                            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}));
                } catch (ParseException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }


}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值