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": "未知错误"
    }
}

以及其他几种异常,此处就不一 一列举了,前端根据返回的异常给用户展示不同的页面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值