欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot項(xiàng)目全局異常統(tǒng)一處理案例代碼

 更新時(shí)間:2023年01月29日 09:48:46   作者:hao_kkkkk  
最近在做項(xiàng)目時(shí)需要對(duì)異常進(jìn)行全局統(tǒng)一處理,主要是一些分類入庫以及記錄日志等,因?yàn)轫?xiàng)目是基于Springboot的,所以去網(wǎng)絡(luò)上找了一些博客文檔,然后再結(jié)合項(xiàng)目本身的一些特殊需求做了些許改造,現(xiàn)在記錄下來便于以后查看

最近在做項(xiàng)目時(shí)需要對(duì)異常進(jìn)行全局統(tǒng)一處理,主要是一些分類入庫以及記錄日志等,因?yàn)轫?xiàng)目是基于Springboot的,所以去網(wǎng)絡(luò)上找了一些博客文檔,然后再結(jié)合項(xiàng)目本身的一些特殊需求做了些許改造,現(xiàn)在記錄下來便于以后查看。

在網(wǎng)絡(luò)上找到關(guān)于Springboot全局異常統(tǒng)一處理的文檔博客主要是兩種方案:

1、基于@ControllerAdvice注解的Controller層的全局異常統(tǒng)一處理

以下是網(wǎng)上一位博主給出的代碼示例,該博客地址為:http://www.dbjr.com.cn/article/195669.htm

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * controller 增強(qiáng)器
 *
 * @author sam
 * @since 2017/7/17
 */
@ControllerAdvice
public class MyControllerAdvice {
 
    /**
     * 全局異常捕捉處理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 100);
        map.put("msg", ex.getMessage());
        return map;
    }
    
    /**
     * 攔截捕捉自定義異常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Map myErrorHandler(MyException ex) {
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;
    }
 
}

這個(gè)代碼示例寫的非常淺顯易懂,但是需要注意的是:基于@ControllerAdvice注解的全局異常統(tǒng)一處理只能針對(duì)于Controller層的異常,意思是只能捕獲到Controller層的異常,在service層或者其他層面的異常都不能捕獲。

根據(jù)這段示例代碼以及結(jié)合項(xiàng)目本身的實(shí)際需求,對(duì)該實(shí)例代碼做了稍微改造(其實(shí)幾乎沒做改造,只是業(yè)務(wù)處理不一樣而已):

@ControllerAdvice
public class AdminExceptionHandler {
 
    private static final Logger logger = LoggerFactory.getLogger(AdminExceptionHandler.class);
 
    /**
      * @Author: gmy
      * @Description: 系統(tǒng)異常捕獲處理
      * @Date: 16:07 2018/5/30
      */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public APIResponse javaExceptionHandler(Exception ex) {//APIResponse是項(xiàng)目中對(duì)外統(tǒng)一的出口封裝,可以根據(jù)自身項(xiàng)目的需求做相應(yīng)更改
        logger.error("捕獲到Exception異常",ex);
        //異常日志入庫
 
        return new APIResponse(APIResponse.FAIL,null,ex.getMessage());
    }
 
    /**
      * @Author: gmy
      * @Description: 自定義異常捕獲處理
      * @Date: 16:08 2018/5/30
      */
    @ResponseBody
    @ExceptionHandler(value = MessageCenterException.class)//MessageCenterException是自定義的一個(gè)異常
    public APIResponse messageCenterExceptionHandler(MessageCenterException ex) {
        logger.error("捕獲到MessageCenterException異常",ex.getException());
        //異常日志入庫
 
        return ex.getApiResponse();
    }
 
}
public class MessageCenterException extends RuntimeException {
 
    public MessageCenterException(APIResponse apiResponse, Exception exception){
        this.apiResponse = apiResponse;
        this.exception = exception;
    }
 
    private Exception exception;
    private APIResponse apiResponse;
 
    public Exception getException() {
        return exception;
    }
 
    public void setException(Exception exception) {
        this.exception = exception;
    }
 
    public APIResponse getApiResponse() {
        return apiResponse;
    }
 
    public void setApiResponse(APIResponse apiResponse) {
        this.apiResponse = apiResponse;
    }
}

經(jīng)過測(cè)試發(fā)現(xiàn)可以捕獲到Controller層的異常,當(dāng)前前提是Controller層沒有對(duì)異常進(jìn)行catch處理,如果Controller層對(duì)異常進(jìn)行了catch處理,那么在這里就不會(huì)捕獲到Controller層的異常了,所以這一點(diǎn)要特別注意。

在實(shí)際測(cè)試中還發(fā)現(xiàn),如果在Controller中不做異常catch處理,在service中拋出異常(service中也不錯(cuò)異常catch處理),那么也是可以在這里捕獲到異常的。

2、基于Springboot自身的全局異常統(tǒng)一處理,主要是實(shí)現(xiàn)ErrorController接口或者繼承AbstractErrorController抽象類或者繼承BasicErrorController類

以下是網(wǎng)上一位博主給出的示例代碼,博客地址為:http://www.dbjr.com.cn/article/110536.htm

@Controller
@RequestMapping(value = "error")
@EnableConfigurationProperties({ServerProperties.class})
public class ExceptionController implements ErrorController {
 
    private ErrorAttributes errorAttributes;
 
    @Autowired
    private ServerProperties serverProperties;
 
 
    /**
     * 初始化ExceptionController
     * @param errorAttributes
     */
    @Autowired
    public ExceptionController(ErrorAttributes errorAttributes) {
        Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
        this.errorAttributes = errorAttributes;
    }
 
 
    /**
     * 定義404的ModelAndView
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(produces = "text/html",value = "404")
    public ModelAndView errorHtml404(HttpServletRequest request,
                                  HttpServletResponse response) {
        response.setStatus(getStatus(request).value());
        Map<String, Object> model = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.TEXT_HTML));
        return new ModelAndView("error/404", model);
    }
 
    /**
     * 定義404的JSON數(shù)據(jù)
     * @param request
     * @return
     */
    @RequestMapping(value = "404")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error404(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.TEXT_HTML));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }
 
    /**
     * 定義500的ModelAndView
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(produces = "text/html",value = "500")
    public ModelAndView errorHtml500(HttpServletRequest request,
                                  HttpServletResponse response) {
        response.setStatus(getStatus(request).value());
        Map<String, Object> model = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.TEXT_HTML));
        return new ModelAndView("error/500", model);
    }
 
 
    /**
     * 定義500的錯(cuò)誤JSON信息
     * @param request
     * @return
     */
    @RequestMapping(value = "500")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error500(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.TEXT_HTML));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }
 
 
    /**
     * Determine if the stacktrace attribute should be included.
     * @param request the source request
     * @param produces the media type produced (or {@code MediaType.ALL})
     * @return if the stacktrace attribute should be included
     */
    protected boolean isIncludeStackTrace(HttpServletRequest request,
                                          MediaType produces) {
        ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
        if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
            return getTraceParameter(request);
        }
        return false;
    }
 
 
    /**
     * 獲取錯(cuò)誤的信息
     * @param request
     * @param includeStackTrace
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return this.errorAttributes.getErrorAttributes(requestAttributes,
                includeStackTrace);
    }
 
    /**
     * 是否包含trace
     * @param request
     * @return
     */
    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
    }
 
    /**
     * 獲取錯(cuò)誤編碼
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
 
    /**
     * 實(shí)現(xiàn)錯(cuò)誤路徑,暫時(shí)無用
     * @see ExceptionMvcAutoConfiguration#containerCustomizer()
     * @return
     */
    @Override
    public String getErrorPath() {
        return "";
    }
 
}

該示例寫的也是非常簡(jiǎn)單明了的,但是結(jié)合本身項(xiàng)目的實(shí)際需求,也是不能直接拿來用的,需要做相應(yīng)的改造,改造主要有以下方面:

1、因?yàn)轫?xiàng)目是前后端分離的,所以Controller層不會(huì)有ModelAndView返回類型,需要返回自身的APIResponse返回類型

2、項(xiàng)目需要統(tǒng)計(jì)全部的異常,而不只是404或者500的異常

3、捕獲到異常之后需要做特殊化的業(yè)務(wù)處理

所以基于以上幾方面對(duì)示例代碼做了改造,具體改造代碼如下:

/**
 * @Author: gmy
 * @Description: Springboot全局異常統(tǒng)一處理
 * @Date: 2018/5/30
 * @Time: 16:41
 */
@RestController
@EnableConfigurationProperties({ServerProperties.class})
public class ExceptionController implements ErrorController {
 
    private ErrorAttributes errorAttributes;
 
    @Autowired
    private ServerProperties serverProperties;
 
 
    /**
     * 初始化ExceptionController
     * @param errorAttributes
     */
    @Autowired
    public ExceptionController(ErrorAttributes errorAttributes) {
        Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
        this.errorAttributes = errorAttributes;
    }
 
 
    @RequestMapping(value = "/error") 
    @ResponseBody
    public APIResponse error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return new APIResponse(APIResponse.FAIL,null,body.get("message").toString());
    }
 
 
 
 
    /**
     * Determine if the stacktrace attribute should be included.
     * @param request the source request
     * @param produces the media type produced (or {@code MediaType.ALL})
     * @return if the stacktrace attribute should be included
     */
    protected boolean isIncludeStackTrace(HttpServletRequest request,
                                          MediaType produces) {
        ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
        if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
            return getTraceParameter(request);
        }
        return false;
    }
 
 
    /**
     * 獲取錯(cuò)誤的信息
     * @param request
     * @param includeStackTrace
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return this.errorAttributes.getErrorAttributes(requestAttributes,
                includeStackTrace);
    }
 
    /**
     * 是否包含trace
     * @param request
     * @return
     */
    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
    }
 
    /**
     * 獲取錯(cuò)誤編碼
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
 
    /**
     * 實(shí)現(xiàn)錯(cuò)誤路徑,暫時(shí)無用
     * @return
     */
    @Override
    public String getErrorPath() {
        return "";
    }
 
}

經(jīng)過測(cè)試,可以捕獲到所有層面上的異常,當(dāng)前前提仍然是沒有對(duì)異常進(jìn)行catch處理,否則這里也是捕獲不到

以上為網(wǎng)絡(luò)上常用的兩種全局異常統(tǒng)一處理方案,經(jīng)過實(shí)際測(cè)試發(fā)現(xiàn)都可以實(shí)現(xiàn)滿足要求。

其實(shí)基于AOP也可以實(shí)現(xiàn)異常的全局處理,自己相應(yīng)的做了測(cè)試發(fā)現(xiàn)也滿足要求,相應(yīng)的代碼如下:

/**
 * @Author: gmy
 * @Description: 基于AOP的全局異常統(tǒng)一處理
 * @Date: 2018/6/1
 * @Time: 13:46
 */
@Component
@Aspect
public class ExceptionAspectController {
    public static final Logger logger = LoggerFactory.getLogger(ExceptionAspectController.class);
 
    @Pointcut("execution(* com.test.test.*.*(..))")//此處基于自身項(xiàng)目的路徑做具體的設(shè)置
    public void pointCut(){}
 
    @Around("pointCut()")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) {
        Stopwatch stopwatch = Stopwatch.createStarted();
 
        APIResponse<?> apiResponse;
        try {
            logger.info("執(zhí)行Controller開始: " + pjp.getSignature() + " 參數(shù):" + Lists.newArrayList(pjp.getArgs()).toString());
            apiResponse = (APIResponse<?>) pjp.proceed(pjp.getArgs());
            logger.info("執(zhí)行Controller結(jié)束: " + pjp.getSignature() + ", 返回值:" + apiResponse.toString());
            logger.info("耗時(shí):" + stopwatch.stop().elapsed(TimeUnit.MILLISECONDS) + "(毫秒).");
        } catch (Throwable throwable) {
            apiResponse = handlerException(pjp, throwable);
        }
 
        return apiResponse;
    }
 
    private APIResponse<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        APIResponse<?> apiResponse = null;
        if(e.getClass().isAssignableFrom(MessageCenterException.class) ){
            MessageCenterException messageCenterException = (MessageCenterException)e;
            logger.error("RuntimeException{方法:" + pjp.getSignature() + ", 參數(shù):" + pjp.getArgs() + ",異常:" + messageCenterException.getException().getMessage() + "}", e);
            apiResponse = messageCenterException.getApiResponse();
        } else if (e instanceof RuntimeException) {
            logger.error("RuntimeException{方法:" + pjp.getSignature() + ", 參數(shù):" + pjp.getArgs() + ",異常:" + e.getMessage() + "}", e);
            apiResponse = new APIResponse(APIResponse.FAIL,null,e.getMessage());
        } else {
            logger.error("異常{方法:" + pjp.getSignature() + ", 參數(shù):" + pjp.getArgs() + ",異常:" + e.getMessage() + "}", e);
            apiResponse = new APIResponse(APIResponse.FAIL,null,e.getMessage());
        }
 
        return apiResponse;
    }
}

經(jīng)過測(cè)試,在執(zhí)行切點(diǎn)中配置的路徑中的方法有異常時(shí),可以被這里捕獲到。

以上是自己了解到并且親自測(cè)試可行的全局異常統(tǒng)一處理方案,如果各位博友有什么問題或者有什么新的方案可以一塊探討下

2018/11/28最新編輯

經(jīng)過一段時(shí)間的使用,現(xiàn)在項(xiàng)目里已經(jīng)統(tǒng)一使用AOP方式來做全局異常統(tǒng)一處理了,選用AOP方式主要是因?yàn)锳OP不只可以做全局異常統(tǒng)一處理還可以統(tǒng)一打印接口請(qǐng)求入?yún)⒑头祷亟Y(jié)果日志,打印接口訪問性能日志,處理sql注入攻擊以及處理入?yún)⑻厥庾址葐栴}

下面貼出代碼,供大家參考,也僅供參考

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
 
/**
 * @Author: gmy
 * @Description: 調(diào)用接口打印性能日志以及接口報(bào)錯(cuò)之后記錄錯(cuò)誤日志
 * @Date: 2018/9/20
 * @Time: 15:16
 */
@Component
@Aspect
public class InterfaceRequestErrrorAndPerformanceLog {
 
    public static final Logger logger = LoggerFactory.getLogger(InterfaceRequestErrrorAndPerformanceLog.class);
 
    @Value("${dc.log.bad.value:3000}")
    private int performanceBadValue;
 
    @Resource
    private RabbitMQService rabbitMQService;
    @Resource
    private InterfaceErrorService interfaceErrorService;
 
    @Pointcut("execution(* test.test.test.test.test.controller.*.*.*(..))")
    public void pointCut(){}
 
    @Around("pointCut()")
    public APIResponse handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable{
        Stopwatch stopwatch = Stopwatch.createStarted();
 
        APIResponse apiResponse;
        try {
            logger.info("執(zhí)行Controller開始: " + pjp.getSignature() + " 參數(shù):" + Lists.newArrayList(pjp.getArgs()).toString());
            //處理入?yún)⑻厥庾址蛃ql注入攻擊
            checkRequestParam(pjp);
            //執(zhí)行訪問接口操作
            apiResponse = (APIResponse) pjp.proceed(pjp.getArgs());
            try{
                logger.info("執(zhí)行Controller結(jié)束: " + pjp.getSignature() + ", 返回值:" + JSONObject.toJSONString(apiResponse));
                //此處將日志打印放入try-catch是因?yàn)轫?xiàng)目中有些對(duì)象實(shí)體bean過于復(fù)雜,導(dǎo)致序列化為json的時(shí)候報(bào)錯(cuò),但是此處報(bào)錯(cuò)并不影響主要功能使用,只是返回結(jié)果日志沒有打印,所以catch中也不做拋出異常處理
            }catch (Exception ex){
                logger.error(pjp.getSignature()+" 接口記錄返回結(jié)果失??!,原因?yàn)椋簕}",ex.getMessage());
            }
            Long consumeTime = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
            logger.info("耗時(shí):" + consumeTime + "(毫秒).");
            //當(dāng)接口請(qǐng)求時(shí)間大于3秒時(shí),標(biāo)記為異常調(diào)用時(shí)間,并記錄入庫
            if(consumeTime > performanceBadValue){
                DcPerformanceEntity dcPerformanceEntity = new DcPerformanceEntity();
                dcPerformanceEntity.setInterfaceName(pjp.getSignature().toString());
                dcPerformanceEntity.setRequestParam(Lists.newArrayList(pjp.getArgs()).toString());
                dcPerformanceEntity.setConsumeTime(consumeTime + "毫秒");
                RabbitMQMessageTarget mqTarget = RabbitMQMessageTarget.createFanoutTarget(ProjectConstants.DC_KEY_EXCHANGE_PERFORMANCE, new String[] { ProjectConstants.DC_KEY_QUEUE_PERFORMANCE});
                rabbitMQService.send(mqTarget, JSON.toJSONString(dcPerformanceEntity));
            }
        } catch (Exception throwable) {
            apiResponse = handlerException(pjp, throwable);
        }
 
        return apiResponse;
    }
 
    /**
      * @Author: gmy
      * @Description: 處理接口調(diào)用異常
      * @Date: 15:13 2018/10/25
      */
    private APIResponse handlerException(ProceedingJoinPoint pjp, Throwable e) {
        APIResponse apiResponse;
        if(e.getClass().isAssignableFrom(ProjectException.class) ){
            //ProjectException為自定義異常類,項(xiàng)目中Controller層會(huì)把所有的異常都catch掉,并手工封裝成ProjectException拋出來,這樣做的目的是ProjectException會(huì)記錄拋出異常接口的路徑,名稱以及請(qǐng)求參數(shù)等等,有助于錯(cuò)誤排查
            ProjectException projectException = (ProjectException)e;
            logger.error("捕獲到ProjectException異常:",JSONObject.toJSONString(projectException.getDcErrorEntity()));
            RabbitMQMessageTarget mqTarget = RabbitMQMessageTarget.createFanoutTarget(ProjectConstants.DC_KEY_EXCHANGE_INTERFACE_ERROR, new String[] { ProjectConstants.DC_KEY_QUEUE_INTERFACE_ERROR});
            rabbitMQService.send(mqTarget, JSON.toJSONString(dataCenterException.getDcErrorEntity()));
            apiResponse = new APIResponse(APIResponse.FAIL,null,projectException.getDcErrorEntity().getErrorMessage());
        } else if (e instanceof RuntimeException) {
            logger.error("RuntimeException{方法:" + pjp.getSignature() + ", 參數(shù):" + pjp.getArgs() + ",異常:" + e.getMessage() + "}", e);
            apiResponse = new APIResponse(APIResponse.FAIL,null,e.getMessage());
        } else {
            logger.error("異常{方法:" + pjp.getSignature() + ", 參數(shù):" + pjp.getArgs() + ",異常:" + e.getMessage() + "}", e);
            apiResponse = new APIResponse(APIResponse.FAIL,null,e.getMessage());
        }
 
        return apiResponse;
    }
 
    /**
      * @Author: gmy
      * @Description: 處理入?yún)⑻厥庾址蛃ql注入攻擊
      * @Date: 15:37 2018/10/25
      */
    private void checkRequestParam(ProceedingJoinPoint pjp){
        String str = String.valueOf(pjp.getArgs());
        if (!IllegalStrFilterUtil.sqlStrFilter(str)) {
            logger.info("訪問接口:" + pjp.getSignature() + ",輸入?yún)?shù)存在SQL注入風(fēng)險(xiǎn)!參數(shù)為:" + Lists.newArrayList(pjp.getArgs()).toString());
            DcErrorEntity dcErrorEntity = interfaceErrorService.processDcErrorEntity(pjp.getSignature() + "",Lists.newArrayList(pjp.getArgs()).toString(),"輸入?yún)?shù)存在SQL注入風(fēng)險(xiǎn)!");
            throw new DataCenterException(dcErrorEntity);
        }
        if (!IllegalStrFilterUtil.isIllegalStr(str)) {
            logger.info("訪問接口:" + pjp.getSignature() + ",輸入?yún)?shù)含有非法字符!,參數(shù)為:" + Lists.newArrayList(pjp.getArgs()).toString());
            DcErrorEntity dcErrorEntity = interfaceErrorService.processDcErrorEntity(pjp.getSignature() + "",Lists.newArrayList(pjp.getArgs()).toString(),"輸入?yún)?shù)含有非法字符!");
            throw new DataCenterException(dcErrorEntity);
        }
    }
 
}

代碼中使用了一些其他的工具類,比如IllegalStrFilterUtil等,我也把代碼貼出來

import org.slf4j.LoggerFactory;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * @Author: gmy
 * @Description: 特殊字符檢測(cè)工具(防止傳入非法字符和sql注入攻擊)
 * @Date: 2018/10/25
 * @Time: 15:08
 */
public class IllegalStrFilterUtil {
    private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(IllegalStrFilterUtil.class);
 
    private static final String REGX = "!|!|@|◎|#|#|(\\$)|¥|%|%|(\\^)|……|(\\&)|※|(\\*)|×|(\\()|(|(\\))|)|_|——|(\\+)|+|(\\|)|§ ";
 
    /**
     * 對(duì)常見的sql注入攻擊進(jìn)行攔截
     *
     * @param sInput
     * @return
     *  true 表示參數(shù)不存在SQL注入風(fēng)險(xiǎn)
     *  false 表示參數(shù)存在SQL注入風(fēng)險(xiǎn)
     */
    public static Boolean sqlStrFilter(String sInput) {
        if (sInput == null || sInput.trim().length() == 0) {
            return false;
        }
        sInput = sInput.toUpperCase();
 
        if (sInput.indexOf("DELETE") >= 0 || sInput.indexOf("ASCII") >= 0 || sInput.indexOf("UPDATE") >= 0 || sInput.indexOf("SELECT") >= 0
                || sInput.indexOf("'") >= 0 || sInput.indexOf("SUBSTR(") >= 0 || sInput.indexOf("COUNT(") >= 0 || sInput.indexOf(" OR ") >= 0
                || sInput.indexOf(" AND ") >= 0 || sInput.indexOf("DROP") >= 0 || sInput.indexOf("EXECUTE") >= 0 || sInput.indexOf("EXEC") >= 0
                || sInput.indexOf("TRUNCATE") >= 0 || sInput.indexOf("INTO") >= 0 || sInput.indexOf("DECLARE") >= 0 || sInput.indexOf("MASTER") >= 0) {
            Logger.error("該參數(shù)怎么SQL注入風(fēng)險(xiǎn):sInput=" + sInput);
            return false;
        }
        Logger.info("通過sql檢測(cè)");
        return true;
    }
 
    /**
     * 對(duì)非法字符進(jìn)行檢測(cè)
     *
     * @param sInput
     * @return
     *  true 表示參數(shù)不包含非法字符
     *  false 表示參數(shù)包含非法字符
     */
    public static Boolean isIllegalStr(String sInput) {
 
        if (sInput == null || sInput.trim().length() == 0) {
            return false;
        }
        sInput = sInput.trim();
        Pattern compile = Pattern.compile(REGX, Pattern.CASE_INSENSITIVE);
        Matcher matcher = compile.matcher(sInput);
        Logger.info("通過字符串檢測(cè)");
        return matcher.find();
    }
}

以上代碼中涉及到真實(shí)項(xiàng)目信息的內(nèi)容我都做了相應(yīng)修改,代碼僅供技術(shù)交流使用。

到此這篇關(guān)于Springboot項(xiàng)目全局異常統(tǒng)一處理的文章就介紹到這了,更多相關(guān)Springboot全局異常處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 用SpringMVC編寫一個(gè)HelloWorld的詳細(xì)過程

    用SpringMVC編寫一個(gè)HelloWorld的詳細(xì)過程

    SpringMVC是Spring的一個(gè)后續(xù)產(chǎn)品,是Spring的一個(gè)子項(xiàng)目<BR>SpringMVC?是?Spring?為表述層開發(fā)提供的一整套完備的解決方案,本文我們將用SpringMVC編寫一個(gè)HelloWorld,文中有詳細(xì)的編寫過程,需要的朋友可以參考下
    2023-08-08
  • JAVA使用DBUtils操作數(shù)據(jù)庫

    JAVA使用DBUtils操作數(shù)據(jù)庫

    這篇文章主要介紹了JAVA使用DBUtils操作數(shù)據(jù)庫的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家學(xué)習(xí)JAVA,感興趣的朋友可以了解下
    2020-07-07
  • JAVA實(shí)現(xiàn)用戶抽獎(jiǎng)功能(附完整代碼)

    JAVA實(shí)現(xiàn)用戶抽獎(jiǎng)功能(附完整代碼)

    這篇文章主要給大家介紹了關(guān)于JAVA實(shí)現(xiàn)用戶抽獎(jiǎng)功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • java使用正則表達(dá)校驗(yàn)手機(jī)號(hào)碼示例(手機(jī)號(hào)碼正則)

    java使用正則表達(dá)校驗(yàn)手機(jī)號(hào)碼示例(手機(jī)號(hào)碼正則)

    這篇文章主要介紹了java使用正則表達(dá)校驗(yàn)手機(jī)號(hào)碼示例,可校驗(yàn)三個(gè)號(hào)碼段:13*、15*、18*,大家根據(jù)自己的需要增加自己的號(hào)碼段就可以了
    2014-03-03
  • Spring中的注解@Value("#{}")與@Value("${}")的區(qū)別介紹

    Spring中的注解@Value("#{}")與@Value("${}")的區(qū)別

    這篇文章主要介紹了Spring中的注解@Value(“#{}“)與@Value(“${}“)的區(qū)別到底是什么,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-06-06
  • 淺析Java隨機(jī)數(shù)與定時(shí)器

    淺析Java隨機(jī)數(shù)與定時(shí)器

    本篇文章給大家分析了Java隨機(jī)數(shù)與定時(shí)器的實(shí)現(xiàn)原理以及代碼分享,有需要的讀者參考下吧。
    2018-02-02
  • Spring mvc Controller和RestFul原理解析

    Spring mvc Controller和RestFul原理解析

    這篇文章主要介紹了Spring mvc Controller和RestFul原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • IDEA神器一鍵查看Java字節(jié)碼及其他類信息插件

    IDEA神器一鍵查看Java字節(jié)碼及其他類信息插件

    這篇文章主要為大家介紹了一款I(lǐng)DEA神器,可以一鍵查看Java字節(jié)碼及其他類信息,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-01-01
  • Springboot實(shí)現(xiàn)人臉識(shí)別與WebSocket長(zhǎng)連接的實(shí)現(xiàn)代碼

    Springboot實(shí)現(xiàn)人臉識(shí)別與WebSocket長(zhǎng)連接的實(shí)現(xiàn)代碼

    這篇文章主要介紹了Springboot實(shí)現(xiàn)人臉識(shí)別與WebSocket長(zhǎng)連接的實(shí)現(xiàn),本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2023-11-11
  • 深入理解Spring Cloud Zuul過濾器

    深入理解Spring Cloud Zuul過濾器

    這篇文章主要給大家介紹了關(guān)于Spring Cloud Zuul過濾器的相關(guān)資料,通過閱讀本文您將了解:Zuul過濾器類型與請(qǐng)求生命周期、如何編寫Zuul過濾器、如何禁用Zuul過濾器和Spring Cloud為Zuul編寫的過濾器及其功能,需要的朋友可以參考下。
    2017-02-02

最新評(píng)論