在很多业务场景中,会出现各种各样的异常,比如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": "未知错误"
}
}
以及其他几种异常,此处就不一 一列举了,前端根据返回的异常给用户展示不同的页面。