@ControllerAdvice + @ExceptionHandler 全局异常处理

1、 定义异常类

//这里只传一个参   可以自己扩展
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = 3416547891266313424L;

    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public BusinessException(String message) {
        this.message = message;
    }
}

2、定义异常处理类

//@ControllerAdvice  声明全局异常处理类 
//@ExceptionHandler  声明异常处理方法 

import com.qingqing.bpt.domain.common.ResultDO;
import com.qingqing.bpt.exception.common.BusinessException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class BusinessExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @SuppressWarnings("rawtypes")
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exceptionResponse(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        String accept = request.getHeader("Accept");
        response.setContentType("text/html; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        ResultDO resultDO = new ResultDO();
        resultDO.setResult(false);
        if (accept.contains("application/json")) {
            //遇到自定义异常类(BusinessException)执行这里
            if (ex instanceof BusinessException) {
                BusinessException e = (BusinessException) ex;
                resultDO.setResultMsg(e.getMessage());
            } else {
                logger.error("", ex);
                resultDO.setResultMsg("系统异常:" + ex.getMessage());
            }
            return resultDO;
        }
        //shiro权限验证失败后跳转
        if(ex instanceof UnauthorizedException) {
            try {
                response.sendRedirect("/bpt/login/noPermission.do");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            PrintWriter out = null;
            try {
                out = response.getWriter();
                if (ex instanceof BusinessException) {
                    BusinessException e = (BusinessException) ex;
                    out.println(e.getMessage());
                } else {
                    logger.error("", ex);
                    out.println(ex.getMessage());
                }
            } catch (IOException e1) {
            } finally {
                out.flush();
                out.close();
            }
            return "";
        }
    }
}

3、使用

需要作为异常处理的地方可以这么用,很方便
throw new BusinessException("该数据不存在");

你可能感兴趣的:(Java)