{{userInfo.nickname}}
用户设置 退出登录

{{wikiTitle}}

全局异常处理

全局异常处理

项目中的异常在GlobalExceptionHandler类中进行统一的拦截处理

捕获到的异常会在doLog方法中存储进eb_exception_log表中,方便对异常进行回溯处理。

当然在这里,如果觉得所有异常都进表会产生无效数据,校验性的异常可以不进行存储,只需判断e.getCode()值不为空,并且排除特定code值即可。

public class GlobalExceptionHandler {

//    private static String REQUESTBODY = "requestBodyMessage";

    @Autowired
    private ExceptionLogService exceptionLogService;

    /**
     * 拦截表单参数校验
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({BindException.class})
    public CommonResult bindException(HttpServletRequest request, BindException e) {
        doLog(request, e);
        BindingResult bindingResult = e.getBindingResult();
        return CommonResult.failed(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

    /**
     * 拦截JSON参数校验
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult bindException(HttpServletRequest request, MethodArgumentNotValidException e) {
        doLog(request, e);
        BindingResult bindingResult = e.getBindingResult();
        return CommonResult.failed(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

    /**
     * 拦截参数类型不正确
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public CommonResult bindException(HttpServletRequest request, HttpMediaTypeNotSupportedException e) {
        doLog(request, e);
        return CommonResult.failed().setMessage(Objects.requireNonNull(e.getMessage()));
    }

    /**
     * 错误SQL语句异常
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    public CommonResult handleBadSqlGrammarException(HttpServletRequest request, BadSqlGrammarException e) {
        doLog(request, e);
        return CommonResult.failed().setMessage("服务器数据异常,请联系管理员");
    }

    /**
     * 拦截表示违反数据库的完整性约束导致的异常
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    public CommonResult handleDataIntegrityViolationException(HttpServletRequest request, DataIntegrityViolationException e) {
        doLog(request, e);
        return CommonResult.failed().setMessage( "服务器数据异常,请联系管理员");
    }

    /**
     * 拦截违反数据库的非完整性约束导致的异常,可能也会拦截一些也包括 SQL 语句错误、连接问题、权限问题等各种数据库异常
     */
    @ExceptionHandler(UncategorizedSQLException.class)
    public CommonResult handleUncategorizedSqlException(HttpServletRequest request, UncategorizedSQLException e) {
        doLog(request, e);
        return CommonResult.failed().setMessage("服务器数据异常,请联系管理员");
    }

    //声明要捕获的异常
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public <T> CommonResult<?> defaultExceptionHandler(HttpServletRequest request, Exception e) {
        doLog(request, e);
        e.printStackTrace();
        if (e instanceof CrmebException) {
            return CommonResult.failed().setMessage(Objects.requireNonNull(e.getMessage()));
        }
        if (e instanceof MissingServletRequestParameterException) {
            return CommonResult.failed().setMessage(Objects.requireNonNull(e.getMessage()));
        }
        //未知错误
        return CommonResult.failed().setMessage(e.getMessage());
    }

    /**
     * 打印日志
     */
    private void doLog(HttpServletRequest request, Exception e) {
        log.error("捕获到异常:", e);
        // 加入数据库日志记录
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        // 异常的详情
        String expDetail = sw.toString();

        try {
            sw.close();
        } catch (IOException ioException) {
            log.error("异常日志:关闭异常详情Writer异常");
        }

        // 异常的url
        String expUrl = request.getRequestURI();

        // 异常的参数 暂时不记录入参
//        Object body = request.getAttribute(REQUESTBODY);
//        String expParams = ObjectUtil.isNotNull(body) ? body.toString() : "";

        // 异常的类型
        String expType = e.getClass().getName();

        // 异常的类名
        StackTraceElement stackTraceElement = e.getStackTrace()[0];
        String expController = stackTraceElement.getClassName();

        // 异常的方法名
        String expMethod = stackTraceElement.getMethodName();

        ExceptionLog exceptionLog = new ExceptionLog();
        exceptionLog.setExpUrl(expUrl);
//        exceptionLog.setExpParams(expParams);
        exceptionLog.setExpParams("");
        exceptionLog.setExpType(expType);
        exceptionLog.setExpController(expController);
        exceptionLog.setExpMethod(expMethod);
        exceptionLog.setExpDetail(expDetail);

        exceptionLogService.save(exceptionLog);
    }
}
{{cateWiki.like_num}}人点赞
0人点赞
评论({{cateWiki.comment_num}}) {{commentWhere.order ? '评论从旧到新':'评论从新到旧'}} {{cateWiki.page_view_num}}人看过该文档
评论(0) {{commentWhere.order ? '评论从旧到新':'评论从新到旧'}} 254人看过该文档
评论
{{item.user ? item.user.nickname : ''}} (自评)
{{item.content}}
{{item.create_time}} 删除
{{item.like ? item.like.like_num : 0}} {{replyIndex == index ? '取消回复' : '回复'}}
评论
{{items.user ? items.user.nickname : '暂无昵称'}} (自评)
{{items.content}}
{{items.create_time}} 删除
{{items.like ? items.like.like_num : 0}} {{replyIndexJ == (index+'|'+indexJ) ? '取消回复' : '回复'}}
评论
目录
  • {{item}}