springboot處理異常終極解決方案,404、405等及其他異常捕捉

在很多業務場景中,會出現各種各樣的異常,比如404,這在用戶體驗上非常不好,接口404前端無法捕捉是什麼原因,對接口及用戶很不友好,如果頁面報404我們直接給接口返回json格式的錯誤,這樣有利於前端去處理並展示相應的引導頁面。

1、首先在application.properties配置404頁面的攔截

#出現錯誤時, 直接拋出異常
spring.mvc.throw-exception-if-no-handler-found=true
#不要爲我們工程中的資源文件建立映射
spring.resources.add-mappings=false

2、然後就是異常處理代碼

GlobalExceptionHandler.java
import com.neo.error.BusinessException;
import com.neo.error.EmBusinessError;
import com.neo.response.CommonReturnType;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date: 2020/4/3 10:42
 * @Author: Rision
 * @Description:404\405\其他異常
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonReturnType doError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Exception ex){
        ex.printStackTrace();
        Map<String,Object> responseData = new HashMap<>();
        if(ex instanceof BusinessException){
            BusinessException businessException = (BusinessException) ex;
            responseData.put("errCode",businessException.getErrCode());
            responseData.put("errMsg",businessException.getErrMsg());
        }else if(ex instanceof ServletRequestBindingException){
            responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg","url綁定路由問題");
        }else if(ex instanceof NoHandlerFoundException){
            responseData.put("errCode",EmBusinessError.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg","沒有找到對應的訪問路徑");
        }else {
            responseData.put("errCode",EmBusinessError.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg",EmBusinessError.UNKNOWN_ERROR.getErrMsg());
        }
        return CommonReturnType.create(responseData);
    }
}

裏面用到的包裝類,這個可以自己封裝,沒什麼技術含量

import com.neo.error.BusinessException;
import com.neo.error.EmBusinessError;
import com.neo.response.CommonReturnType;

3、然後看效果

(1)、訪問一個找不到的路徑,404類型的

{
    "status": "success",
    "data": {
        "errCode": 10002,
        "errMsg": "沒有找到對應的訪問路徑"
    }
}

(2)、系統未知異常

{
    "status": "success",
    "data": {
        "errCode": 10002,
        "errMsg": "未知錯誤"
    }
}

以及其他幾種異常,此處就不一 一列舉了,前端根據返回的異常給用戶展示不同的頁面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章