springboot全局拦截sql异常

起因:非法用户可通过特定的输入(如输入内容超长)等操作,使后台逻辑发生错误,从而使后台sql语句暴露至前台,进而为sql攻击提供条件

springboot全局拦截sql异常_第1张图片

处理流程:经查找com.mysql.cj.jdbc.exceptions的父类为SQLException,在全局异常处理类中增加如下配置,经测试不起作用

@ExceptionHandler(SQLException.class)
public AjaxResult handleSQLException(AccessDeniedException e, HttpServletRequest request)
{
    String requestURI = request.getRequestURI();
    return AjaxResult.error("语句执行异常,请联系管理员");
}

因为ExceptionHandler 只认我们注入的类名称,所以我们的曲线一下,在RuntimeException中进行判断

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        if(e.getCause().toString().startsWith("com.mysql.cj.jdbc.exceptions")){
            return AjaxResult.error(HttpStatus.ERROR, "操作失败!请联系管理员");
        }else{
          return AjaxResult.error(e.getMessage());
        }
    }

结果:

springboot全局拦截sql异常_第2张图片

你可能感兴趣的:(spring,java,后端)