Spring Boot笔记-404错误统一管理

这里有一点要注意:

spring boot错误的页面都会到error的请求中,所以可以用如下的方式统一管理

package com.xxxxx.apc.controller;

import com.apc.apc.utils.ResultUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {

    @Override
    public String getErrorPath() {
        return "error";
    }

    @RequestMapping("/error")
    public Object handleError(HttpServletRequest request){

        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 404){

            Map<String, String> map = new HashMap<>();
            map.put("tip", "can not find page");
            return ResultUtil.error(map);
        }

        return null;
    }

}

运行截图如下:

发布了1312 篇原创文章 · 获赞 2429 · 访问量 185万+

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/104651084