TemplarJQ / KillMall

使用SpringBoot+Mybatis实现的秒杀商城项目
1 stars 1 forks source link

[003-404问题]404异常的处理 #3

Open TemplarJQ opened 5 years ago

TemplarJQ commented 5 years ago

404异常问题的处理

现在的网站对于,比如说前端页面上:

$.ajax({
                type:"POST",
                contentType:"application/x-www-form-urlencoded",
                url:"http://localhost:8090/user/register",
                data:{
                    "telphone": telphone,
                    "otpCode": otpCode,
                    "name": name,
                    "gender": gender,
                    "age": age,
                    "password": password
                },

改为

$.ajax({
                type:"POST",
                contentType:"application/x-www-form-urlencoded",
                url:"http://localhost:8090/user/register1111", <!--这里发生改动-->
                data:{
                    "telphone": telphone,
                    "otpCode": otpCode,
                    "name": name,
                    "gender": gender,
                    "age": age,
                    "password": password
                },

引起的404问题,实际上是无法得到解决的。

TemplarJQ commented 5 years ago

原因分析

前端访问不到的页面根本没有进入任何一个Controller,也就无法引起异常,因此也就没有办法引起BaseController对于异常的处理过程,因此需要改进。

解决办法

加入GobalController的控制:

@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,"fail");
    }
}
TemplarJQ commented 5 years ago

新问题的产生:405问题NoHandlerFoundException

一个正常的请求为:

http://localhost:8090/user/get?id=1

前面过程中我们的GlobalExceptionHandler处理了没有参数的情况

http://localhost:8090/user/get

当我们在url中故意修改错时,是无法处理的

http://localhost:8090/user/get1

解决方案

在application.properties中修改并添加

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false