异常统一处理

一,异常统一处理

1,自定义异常

package com.onloon.scrm.common.exception;

import com.onloon.scrm.common.enums.ResultCodeEnum;
import lombok.Getter;

/**
 * 业务层异常*/
@Getter
public class BusinessException extends RuntimeException {

    /**
     * 错误编码
     */
    private int errorCode = ResultCodeEnum.NORMAL_ERROR.getCode();

    /**
     * 错误数据
     */
    private Object errorData;

    /**
     * 
     */
    private static final long serialVersionUID = -8582206887663268981L;

    public BusinessException() {
        super();
    }

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(ResultCodeEnum resultCodeEnum, String message) {
        super(message);
        this.errorCode = resultCodeEnum.getCode();
    }

    public BusinessException(int errorCode, Object errorData, String message) {
        super(message);
        this.errorCode = errorCode;
        this.errorData = errorData;
    }

    public BusinessException(String message, Throwable cause) {
        super(message, cause);
    }

    public BusinessException(Throwable cause) {
        super(cause);
    }

    protected BusinessException(String message, Throwable cause, boolean enableSuppression,
            boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

2,定义拦截器

package com.onloon.scrm.pc.web.controller;

import com.onloon.scrm.common.beans.Result;
import com.onloon.scrm.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

/**
 * 业务异常统一处理器*/
@ControllerAdvice
@Slf4j
public class BusinessExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public Result<String> exceptionHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        log.info("发生未捕获异常:", e);
        if (e instanceof BusinessException) {
            return Result.failure((BusinessException) e);
        } else if (e instanceof NullPointerException || e instanceof SQLException || e instanceof IllegalStateException) {
            return Result.failure("服务器开小差了,请尽快联系服务人员");
        } else {
            return Result.failure("服务器开小差了,请稍后重试");
        }
    }

}

 

posted @ 2019-01-04 10:14  wanhua.wu  阅读(405)  评论(0编辑  收藏  举报